Basic communication between two fragments

前端 未结 10 2154
我寻月下人不归
我寻月下人不归 2020-11-22 05:00

I have one activity - MainActivity. Within this activity I have two fragments, both of which I created declaratively within the xml.

I am trying to pas

相关标签:
10条回答
  • 2020-11-22 05:29

    Consider my 2 fragments A and B, and Suppose I need to pass data from B to A.

    Then create an interface in B, and pass the data to the Main Activity. There create another interface and pass data to fragment A.

    Sharing a small example:

    Fragment A looks like

    public class FragmentA extends Fragment implements InterfaceDataCommunicatorFromActivity {
    public InterfaceDataCommunicatorFromActivity interfaceDataCommunicatorFromActivity;
    String data;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    
    @Override
    public void updateData(String data) {
        // TODO Auto-generated method stub
        this.data = data;
        //data is updated here which is from fragment B
    }
    
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        try {
            interfaceDataCommunicatorFromActivity = (InterfaceDataCommunicatorFromActivity) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement TextClicked");
        }
    
    }
    
    }
    

    FragmentB looks like

    class FragmentB extends Fragment {
    public InterfaceDataCommunicator interfaceDataCommunicator;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    
        // call this inorder to send Data to interface
        interfaceDataCommunicator.updateData("data");
    }
    
    public interface InterfaceDataCommunicator {
        public void updateData(String data);
    }
    
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        try {
            interfaceDataCommunicator = (InterfaceDataCommunicator) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement TextClicked");
        }
    
    }
    
    }
    

    Main Activity is

    public class MainActivity extends Activity implements InterfaceDataCommunicator {
    public InterfaceDataCommunicatorFromActivity interfaceDataCommunicatorFromActivity;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public void updateData(String data) {
        // TODO Auto-generated method stub
        interfaceDataCommunicatorFromActivity.updateData(data);
    
    }
    
    public interface InterfaceDataCommunicatorFromActivity {
        public void updateData(String data);
    }
    
    }
    
    0 讨论(0)
  • 2020-11-22 05:35

    Learn " setTargetFragment() "

    Where " startActivityForResult() " establishes a relationship between 2 activities, " setTargetFragment() " defines the caller/called relationship between 2 fragments.

    0 讨论(0)
  • 2020-11-22 05:36

    I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment

    Here is an example. Click a TextView on DialogFragment triggers a callback to MainActivity in onTextClicked then grab the MyFagment instance to interact with.

    public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {
    
    private static final String MY_FRAGM = "MY_FRAGMENT";
    private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        getSupportFragmentManager().beginTransaction()
            .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
            .commit();
    
        findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
            }
        });
    }
    
    Toast mToast;
    
    @Override
    public void onClickButton(MyFragment fragment) {
        if (mToast != null)
            mToast.cancel();
        mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
        mToast.show();
    }
    
    @Override
    public void onTextClicked(MyDialogFragment fragment) {
        MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
        if (myFragm != null) {
            myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
        }
    }
    

    }

    0 讨论(0)
  • 2020-11-22 05:37

    Update

    Ignore this answer. Not that it doesn't work. But there are better methods available. Moreover, Android emphatically discourage direct communication between fragments. See official doc. Thanks user @Wahib Ul Haq for the tip.

    Original Answer

    Well, you can create a private variable and setter in Fragment B, and set the value from Fragment A itself,

    FragmentB.java

    private String inputString;
    ....
    ....
    
    public void setInputString(String string){
       inputString = string;
    }
    

    FragmentA.java

    //go to fragment B
    
    FragmentB frag  = new FragmentB();
    frag.setInputString(YOUR_STRING);
    //create your fragment transaction object, set animation etc
    fragTrans.replace(ITS_ARGUMENTS)
    

    Or you can use Activity as you suggested in question..

    0 讨论(0)
提交回复
热议问题