Send data from activity to fragment in Android

前端 未结 20 2712
悲哀的现实
悲哀的现实 2020-11-21 05:13

I have two classes. First is activity, second is a fragment where I have some EditText. In activity I have a subclass with async-task and in method doInBa

20条回答
  •  礼貌的吻别
    2020-11-21 05:38

    The best and convenient approach is calling fragment instance and send data at that time. every fragment by default have instance method

    For example : if your fragment name is MyFragment

    so you will call your fragment from activity like this :

    getSupportFragmentManager().beginTransaction().add(R.id.container, MyFragment.newInstance("data1","data2"),"MyFragment").commit();
    

    *R.id.container is a id of my FrameLayout

    so in MyFragment.newInstance("data1","data2") you can send data to fragment and in your fragment you get this data in MyFragment newInstance(String param1, String param2)

    public static MyFragment newInstance(String param1, String param2) {
            MyFragment fragment = new MyFragment();
            Bundle args = new Bundle();
            args.putString(ARG_PARAM1, param1);
            args.putString(ARG_PARAM2, param2);
            fragment.setArguments(args);
            return fragment;
        }
    

    and then in onCreate method of fragment you'll get the data:

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                mParam1 = getArguments().getString(ARG_PARAM1);
                mParam2 = getArguments().getString(ARG_PARAM2);
            }
        }
    

    so now mParam1 have data1 and mParam2 have data2

    now you can use this mParam1 and mParam2 in your fragment.

提交回复
热议问题