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

kma*_*mur 7 android android-fragments

我有一个片段在onCreateView中使用getArguments()方法来获取一些输入数据.

我在ViewPager中使用这个片段,它工作正常.

当我尝试在不同的活动中重用此片段时,问题就开始了,该活动仅显示此片段.我想将片段添加到activitie的布局中:

<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" />
Run Code Online (Sandbox Code Playgroud)

问题是:如何将Bundle传递给布局中声明的片段?

Asw*_*ran 14

最好的方法是更改​​为FrameLayout并将片段放入代码中.

public void onCreate(...) {

    ScheduleDayFragment fragment = new ScheduleDayFragment();
    fragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction()
                .add(R.id.main_view, fragment).commit();
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是布局文件

<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" />
Run Code Online (Sandbox Code Playgroud)

您是否担心这会以某种方式降低性能?

  • 我最终得到了这个解决方案.我试图找到更优雅的东西,但显然这是不可能的. (3认同)

A S*_*D I 5

我知道答案为时已晚,但我认为有人需要:)

只是在活动覆盖 onAttachFragment()

@Override
public void onAttachFragment(@NonNull Fragment fragment)
{
    super.onAttachFragment(fragment);

    if (fragment.getId() == R.id.frgBlank)
    {
        Bundle b = new Bundle();
        b.putString("msg", "Message");

        fragment.setArguments(b);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在片段 onCreateView 方法中

Bundle b = getArguments();
if (b != null)
{
    Toast.makeText(requireContext(), b.getString("msg"), Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

就这样,希望能帮助别人:)