【问题标题】:Accessing a hardcoded fragment within the activity layout through findById通过 findById 访问活动布局中的硬编码片段
【发布时间】:2020-02-20 07:05:20
【问题描述】:

我能够访问硬编码的预实例化片段,但转换失败。尝试调用setArguments 或调用类上的特定方法。

能够在findViewById(R.id.product); 上拨打Fragment.setArguments 可以解决我的问题

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/product"
        android:name="Product"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/product_fragment" />

</android.support.constraint.ConstraintLayout>

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(savedInstanceState == null) {
            findViewById(R.id.product); // works
            findViewById(R.id.product).findViewById(R.id.subview); // works
            Product frag = (Product) findViewById(R.id.product); // cast fails
        }
    }
}

产品

public class Product extends Fragment {
    // implementation
}

【问题讨论】:

    标签: android


    【解决方案1】:

    findViewById() 仅返回视图。

    你可以使用

    getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)
    

    参考这篇文章。

    https://stackoverflow.com/a/23592993/6854435

    编辑:

    经过一番研究,似乎您不能在使用您的方法附加片段之前调用setArguments

    • 但是,如果您以编程方式添加片段,则可以使用 setArguments

    How do I add a Fragment to an Activity with a programmatically created content view

    【讨论】:

    • 谢谢,那我如何在后期创建场景中访问setArguments 方法传递的参数?
    • 我应该在Fragment类上创建一个自定义方法,并在传递数据时单独调用它吗?
    • 我想如果你使用的是fragment附加后的数据,你可以设置你的自定义方法——stackoverflow.com/questions/13034746/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多