Basic communication between two fragments

前端 未结 10 2166
我寻月下人不归
我寻月下人不归 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:23

    Have a look at the Android developers page: http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

    Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value

    Your Activity implements your interface (See FragmentA below)

    public class YourActivity implements FragmentA.TextClicked{
        @Override
        public void sendText(String text){
            // Get Fragment B
            FraB frag = (FragB)
                getSupportFragmentManager().findFragmentById(R.id.fragment_b);
            frag.updateText(text);
        }
    }
    

    Fragment A defines an Interface, and calls the method when needed

    public class FragA extends Fragment{
    
        TextClicked mCallback;
    
        public interface TextClicked{
            public void sendText(String text);
        }
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
    
            // This makes sure that the container activity has implemented
            // the callback interface. If not, it throws an exception
            try {
                mCallback = (TextClicked) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                    + " must implement TextClicked");
            }
        }
    
        public void someMethod(){
            mCallback.sendText("YOUR TEXT");
        }
    
        @Override
        public void onDetach() {
            mCallback = null; // => avoid leaking, thanks @Deepscorn
            super.onDetach();
        }
    }
    

    Fragment B has a public method to do something with the text

    public class FragB extends Fragment{
    
        public void updateText(String text){
            // Here you have it
        }
    }
    

提交回复
热议问题