布局中声明的Android Fragment,如何设置参数?

标签 android android-fragments

我有一个 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/

相关文章:

android - 传递包而不替换 fragment

java - fragment 点击

java - Android 在另一个异步任务中调用异步任务?

Android:OTG 存储通知与 radio c 冲突

android - 如何在不传递上下文引用的情况下从类中的静态方法访问 Android SharedPreferences?

java - AndroidAnnotations 和 Dagger

android - 无法为 fragment 设置菜单

android - 使用 DatePickerDialog 时冲突 support.v4.app.Fragment 与 app.Fragment

android - 未知来源设置安卓

android - 使用滚动 RecyclerView 时如何在 ViewPager 中隐藏工具栏?