【问题标题】:Android Fragment declared in layout, how to set arguments?布局中声明的Android Fragment,如何设置参数?
【发布时间】:2014-02-19 14:25:12
【问题描述】:

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

我将这个片段与 ViewPager 一起使用,它工作正常。

当我尝试在不同的活动中重用这个片段时,问题就开始了,它只显示了这个片段。我想将片段添加到活动的布局中:

<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传递给layout中声明的fragment?

【问题讨论】:

标签: android android-fragments


【解决方案1】:

最好的方法是将其更改为 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" />

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

【讨论】:

  • 我最终得到了这个解决方案。我试图找到更优雅的东西,但显然这是不可能的。
【解决方案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();
}

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

【讨论】:

    【解决方案3】:

    如果您在布局中坚持使用片段声明,则可以在 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() 调用创建的意图中

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 2013-05-31
      • 1970-01-01
      • 2011-09-21
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      相关资源
      最近更新 更多