我能够访问硬编码的预实例化片段,但强制转换失败。正在尝试调用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>
主要活动
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
}
findViewById((只返回View
您可以使用
getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)
请参阅此帖子。
https://stackoverflow.com/a/23592993/6854435
编辑:
经过一些研究,在使用您的方法附加片段之前,您似乎无法调用setArguments
。
- 但是,如果以编程方式添加片段,则可以执行
setArguments
:
如何使用程序创建的内容视图将片段添加到活动中