Is it possible to pass arguments to a fragment after it's been added to an activity?

前端 未结 3 1452
借酒劲吻你
借酒劲吻你 2020-12-28 13:58

I know that when you\'re first instantiating a fragment you can pass arguments using setArguments(Bundle) and retrieve them in the fragment using getArgum

3条回答
  •  时光取名叫无心
    2020-12-28 14:32

    Yes, if you have called setArguments(bundle) before your fragment becomes active. Then your fragment from there after has a bundle that you can update. To avoid your issue you must update the original bundle and must not invoke setArguments a second time. So following your initial fragment construction, modify fragment arguments with code like

    frg.getArguments().putString("someKey", "someValue");
    

    The arguments will then be available in your fragment and will be persisted and restored during orientation changes and such.

    Note this method is also useful when the fragment is being created via xml in a layout. Ordinarily one would not be able to set arguments on such a fragment; the way to avoid this restriction is to create a no argument constructor which creates the argument bundle like so:

    public MyFragment() {
        this.setArguments(new Bundle());
    }
    

    Later somewhere in your activity's onCreate method you would then do:

    FragmentManager mgr = this.getSupportFragmentManager();
    Fragment frg = mgr.findFragmentById(R.id.gl_frgMyFragment);
    Bundle bdl = frg.getArguments();
    bdl.putSerializable(MyFragment.ATTR_SOMEATTR, someData);
    

    This places data into the argument bundle, which will then be available to code in your fragment.

提交回复
热议问题