Search code examples
javaandroidfragmentsearchviewlistadapter

Updating SearchView in FragA from ListAdapter in FragB?


Scenario: You have two fragments, Fragment A which populates a ListAdapter, Fragment B which contains a SearchView with a ListAdapter.

Question: How does Fragment A update Fragment B's SearchView's ListAdapter?

enter image description here


Solution

  • Fragments should not communicate directly. You should use your activity for communication between child fragments. You can create an interface which will define a contract for communication between fragments.

    public interface UpdateSerachViewList {
        void update(List<> data);
    }
    

    Activity will implement this interface. Activity has access to both fragment1 and fragment 2.

    If you want to send a message from frag1 to frag2 then fragment1 will in onAttach method save activity (Context param) as UpdateSerachViewList handler.

    public class Frag1 extends Fragment {
        private UpdateSerachViewList mCallback;
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mCallback = (UpdateSerachViewList) context; 
    // If exception is throws it measn you want to use frafgment with activity which does not implement communication contract. Design error
        }
    
        @Override
        public void onStart() {
            super.onStart();
            mCallback.update(...);
        }
    }
    

    In Activity you can then call what method you want on Fragment2. Or you can make frag2 also implement contract so you don't have to have direct reference to Frag2 but only to communication contract.