如何在 Fragments 中使用 setArguments() 和 getArguments() 方法?

新手上路,请多包涵

我有 2 个片段:(1)Frag1 (2)Frag2。

片段1

 bundl = new Bundle();
bundl.putStringArrayList("elist", eList);

Frag2 dv = new Frag2();
dv.setArguments(bundl);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.the_fragg,dv);
ft.show(getFragmentManager().findFragmentById(R.id.the_fragg));
ft.addToBackStack(null);
ft.commit();

如何在 Frag2 中获取这些数据?

原文由 Android_programmer_camera 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 771
2 个回答

您有一个名为 getArguments() 的方法属于 Fragment 类。

原文由 codeScriber 发布,翻译遵循 CC BY-SA 3.0 许可协议

以正确的方式实例化片段!

getArguments() setArguments() 在使用静态方法实例化片段时,方法似乎非常有用。

Myfragment.createInstance(String msg)

怎么做?

片段代码

public MyFragment extends Fragment {

    private String displayMsg;
    private TextView text;

    public static MyFragment createInstance(String displayMsg)
    {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.setString("KEY",displayMsg);
        fragment.setArguments(args);           //set
        return fragment;
    }

    @Override
    public void onCreate(Bundle bundle)
    {
        displayMsg = getArguments().getString("KEY"):    // get
    }

    @Override
    public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
        View view = inflater.inflate(R.id.placeholder,parent,false);
        text = (TextView)view.findViewById(R.id.myTextView);
        text.setText(displayMsg)    // show msg
        returm view;
   }

}

假设您想在创建实例时传递一个字符串。这就是你将如何做到的。

 MyFragment.createInstance("This String will be shown in textView");

阅读更多

1) 为什么 Myfragment.getInstance(String msg) 优于 new MyFragment(String msg)?

2) Fragments 上的示例代码

原文由 Rohit Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题