How to pass Arguments to Fragment from Activity

后端 未结 4 1165
既然无缘
既然无缘 2021-01-05 18:37

I have an activity which instantiates and populates a Fragment through a adopter class. I want to pass values/objects to this Fragment adopter class so that i can dictate la

4条回答
  •  借酒劲吻你
    2021-01-05 18:50

    To pass argument to your fragment, it's recommended to create a public static method to instanciate your fragment like :

    public static MyFragment newInstance(String firstArg) {
            MyFragment f = new MyFragment ();
            Bundle args = new Bundle();
            args.putString("ARG1", firstArg);
            f.setArguments(args);
            return f;
        }
    

    And then retrieve your args in onCreateView() method like :

    String arg = getArguments().getString("ARG1");
    

    Use the static method to instanciate a new fragment with your arguments in other fragment or activities like :

    MyFragment f = MyFragment.newInstance(myArg);
    

提交回复
热议问题