How to set target fragment of a dialog when using navigation components

∥☆過路亽.° 提交于 2019-12-04 03:07:32

The recommended pattern for communicating between Fragments with the Navigation Architecture Components is via a shared ViewModel - a ViewModel that lives at the Activity level achieved by retrieving the ViewModel using ViewModelProviders.of(getActivity())

As per the documentation, this offers a number of benefits:

  • The activity does not need to do anything, or know anything about this communication.
  • Fragments don't need to know about each other besides the SharedViewModel contract. If one of the fragments disappears, the other one keeps working as usual.
  • Each fragment has its own lifecycle, and is not affected by the lifecycle of the other one. If one fragment replaces the other one, the UI continues to work without any problems.

To elaborate on the accepted answer:

(1) Create a shared view model that would be used to share data between fragments within that Activity.

public class SharedViewModel extends ViewModel {

    private final MutableLiveData<Double> aDouble = new MutableLiveData<>();

    public void setDouble(Double aDouble) {
        this.aDouble.setValue(aDouble);
    }

    public LiveData<Double> getDouble() {
        return aDouble;
    }
}

(2) Store the data you would like to access in the view model. Note the scope of the view model (getActivity).

SharedViewModel svm =ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
svm.setDouble(someDouble);

(3) Let the fragment implement the dialog's callback interface and load the dialog without setting a target fragment.

fragment.setOnDialogSubmitListener(this);
fragment.show(getActivity().getSupportFragmentManager(), TAG);

(4) Inside the dialog retrieve the data.

SharedViewModel svm =ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
svm.getDouble().observe(this, new Observer<Double>() {
    @Override
    public void onChanged(Double aDouble) {
        // do what ever with aDouble
    }
}); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!