Basic communication between two fragments

前端 未结 10 2152
我寻月下人不归
我寻月下人不归 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:21

    The nicest and recommended way is to use a shared ViewModel.

    https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

    From Google doc:

    public class SharedViewModel extends ViewModel {
    private final MutableLiveData selected = new MutableLiveData();
    
    public void select(Item item) {
        selected.setValue(item);
    }
    
    public LiveData getSelected() {
        return selected;
    }
    }
    
    
    public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
    }
    
    
    public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, { item ->
           // Update the UI.
        });
    }
    }
    

    ps: two fragments never communicate directly

提交回复
热议问题