how to send data from one fragment to another fragment in android?

前端 未结 3 493
一生所求
一生所求 2020-12-12 04:40

Hello I make a simple tab view using pager and fragment . So I have two tabs in my view .In one tab I have list view in which each row have textview and favourite

3条回答
  •  情话喂你
    2020-12-12 05:14

    Suppose you are sending data from FragmentA to FragmentB, then the best practice is to use Interfaces and then communicate between fragment via the container activity. Below is a small snippet that will provide with the skeleton of what i am trying to say:

    Step-1: In your FragmentA define an Interface and override onAttach() method to make it mandatory for your container activity to implement the interface and provide body to its method.

        public interface MyInterfaceListener{
          public void myMethod(yourParameters)//this method will hold parameters which you can then use in your container activity to send it to FragmentB 
    }
    
    private MyInterfaceListener listener;
    @Override
    public void onAttach(Activity activity) {
      super.onAttach(activity);
      if (activity instanceof MyInterfaceListener) {
        listener = (MyInterfaceListener) activity;// This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception 
      } else {
        throw new ClassCastException(activity.toString()
            + " must implemenet MyListFragment.OnItemSelectedListener");
      }
    }
    

    Now, in your FragmentA you can pass value to myMethod() like: if (listener!=null) { listener.myMethod(yourArguments); }

    Step-2: Now, In your container activity implement the callback Interface

    public class MyActivity extends Activity implements MyInterfaceListener{
            @Override
             public void myMethod(yourParameters) {
                  //do your stuff here. do whatever you want to do with the //parameter list which is nothing but data from FragmentA.
                    FragmentB fragment = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.yourFragmentB);
                    fragment.methodInFragmentB(sendDataAsArguments);// calling a method in FragmentB and and sending data as arguments. 
            }
    }
    

    Step-3: In FragmentB have a method say for example methodInFragmentB(yourParameters)

        public void methodInFragmentB(yourParameters){
          //do whatever you want to do with the data..... 
    }
    

    I hope the above description helps. Thanks.

提交回复
热议问题