Below is how i am navigating
from fragment A
to fragment B
using android navigation
@Override
public void onClick(View view) {
int viewId = view.getId();
if (viewId == R.id.btn_proceed) {
Navigation.findNavController(view).navigate(R.id.fragmentB);
}
}
I would like to achieve returning of results from fragmentB
to fragmentA
where for example fragmentB has an EditText that a user keys in text and is returned to fragmentA and set to TextView using android architecture navigation components
According to documentation on returning a result i was able to achieve what i was asking with the code below.
Declare a NavController
private NavController navController;
Inside onViewCreated
method
navController = Navigation.findNavController(view);
MutableLiveData<String> liveData = Objects.requireNonNull(navController.getCurrentBackStackEntry())
.getSavedStateHandle()
.getLiveData("key");
To get result in FragmentA from FragmentB
liveData.observe(getViewLifecycleOwner(), s -> {
tvResult.setText(s);
});
In FragmentB do the following, for example when a button is clicked
@Override
public void onClick(View view) {
int viewId = view.getId();
NavController navController = Navigation.findNavController(view);
if (viewId == R.id.btn_returnResult) {
String etText = editText.getText().toString();
Objects.requireNonNull(navController.getPreviousBackStackEntry())
.getSavedStateHandle().set("key", etText);
navController.navigateUp();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.