[英]launch a fragment with result using navigation architecture components
Below is how i am navigating
from fragment A
to fragment B
using android navigation
下面是我如何使用 android
navigating
从fragment A
navigation
到fragment B
@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我想实现从
fragmentB
到fragmentA
的结果返回,例如 fragmentB 有一个EditText ,用户输入文本并返回到 fragmentA 并使用 android 架构导航组件设置为TextView
According to documentation on returning a result i was able to achieve what i was asking with the code below.根据返回结果的文档,我能够使用下面的代码实现我所要求的。
Declare a NavController声明一个NavController
private NavController navController;
Inside onViewCreated
method onViewCreated
方法内部
navController = Navigation.findNavController(view);
MutableLiveData<String> liveData = Objects.requireNonNull(navController.getCurrentBackStackEntry())
.getSavedStateHandle()
.getLiveData("key");
To get result in FragmentA from FragmentB从FragmentB得到FragmentA的结果
liveData.observe(getViewLifecycleOwner(), s -> {
tvResult.setText(s);
});
In FragmentB do the following, for example when a button is clicked在FragmentB中执行以下操作,例如单击按钮时
@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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.