问题
Let's say that we have two fragments: MainFragment
and SelectionFragment
. The second one is build for selecting some object, e.g. an integer. There are different approaches in receiving result from this second fragment like callbacks, buses etc.
Now, if we decide to use Navigation Architecture Component in order to navigate to second fragment we can use this code:
NavHostFragment.findNavController(this).navigate(R.id.action_selection, bundle)
where bundle
is an instance of Bundle
(of course). As you can see there is no access to SelectionFragment
where we could put a callback. The question is, how to receive a result with Navigation Architecture Component?
回答1:
According to Google: you should try to use shared ViewModel. Check below example from Google:
Shared ViewModel that will contain shared data and can be accessed from different fragments.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
MasterFragment that updates ViewModel:
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);
});
}
}
DetailsFragment that uses shared ViewModel:
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.
});
}
}
来源:https://stackoverflow.com/questions/50754523/how-to-get-a-result-from-fragment-using-navigation-architecture-component