我有一个 fragment ,它在 onCreateView 中使用 getArguments() 方法来获取一些输入数据。
我将这个 fragment 与 ViewPager 一起使用,它工作正常。
当我尝试在另一个仅显示该 fragment 的 Activity 中重用该 fragment 时,问题就出现了。我想将 fragment 添加到 Activity 的布局中:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
android:name="com.example.ScheduleDayFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
问题是:如何将 Bundle 传递给布局中声明的 fragment ?
最佳答案
最好的方法是将 更改为 FrameLayout 并将 fragment 放入代码中。
public void onCreate(...) {
ScheduleDayFragment fragment = new ScheduleDayFragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.add(R.id.main_view, fragment).commit();
...
}
这是布局文件
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
您是否担心这会以某种方式降低性能?
关于布局中声明的Android Fragment,如何设置参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21403040/