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

时间:2014-01-28 10:29:35

标签: 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" />

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

3 个答案:

答案 0 :(得分:12)

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

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" />

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

答案 1 :(得分:2)

如果您坚持在布局中使用片段声明,则可以在Fragment.OnCreateView()中使用此检查

    if (savedInstanceState != null) {
        // value can be restored after Fragment is restored
        value = savedInstanceState.getInt("myValueTag", -1);

    } else if (getArguments() != null) {
        // value is set by Fragment arguments
        value = getArguments().getInt("myValueTag", -1);

    } else if (getActivity() != null && getActivity().getIntent() != null) {
        // value is read from activity intent
        value = getActivity().getIntent().getIntExtra("myValueTag", -1);
    }

最后只需将您的值信息添加到为startActivity()调用

创建的意图中

答案 2 :(得分:2)

我知道答案太迟了,但我认为有人需要它:)

仅在活动中覆盖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);
    }
}

以及onCreateView方法的片段

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

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