java - 通过 setFragmentResult 向另一个 Fragment 发送信息
问题描述
我正在尝试将信息从 Fragment A 的 recyclerView 的 OnClickListener 发送到新创建的 Fragment B 并将其显示在 textView 中。我正在关注 android 的片段到片段通信文档,其中说我应该使用片段结果 API:https ://developer.android.com/guide/fragments/communicate#pass-between-fragments
Fragment A 的 RecyclerView.Adapter 的 OnClickListener 的代码:
@Override
public void onBindViewHolder(@NonNull NoticiaViewHolder holder, int position) {
holder.cardLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
//add things to bundle
bundle.putString("test", "hello");
VistaNoticiaFragment vistaNoticiaFragment = new VistaNoticiaFragment();
FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();
//set bundle in fragmentManager
manager.setFragmentResult("noticiaObject", bundle);
//go to next fragment
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, vistaNoticiaFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
如您所见,我正在尝试使用 setFragmentResult() 将字符串发送到片段 B,并使用 setFragmentResultListener 在那里接收它。
片段 B 的代码:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = view.findViewById(R.id.vistaNoticiaText);
System.out.println("onViewCreated" + foo);
textView.setText(foo);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getParentFragmentManager().setFragmentResultListener("noticiaObject", this, new FragmentResultListener() {
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
// We use a String here, but any type that can be put in a Bundle is supported
String result = bundle.getString("test");
System.out.println("onFragmentResult" + result);
// Do something with the result
foo = result;
}
});
}
输出
I/System.out: onViewCreated null
I/System.out: onFragmentResult hello
当我在 Fragment A 的 recyclerView 中单击一个项目时,会成功创建并加载 Fragment B。但是,如您所见,onFragmentResult 中的代码似乎在 onViewCreated 之后运行,这意味着我无法访问包的内容以将其显示在 Fragment B 的 textView 中。我确实注意到文档是这样说的:
“片段 A 然后接收结果并在片段启动后执行侦听器回调。”
但是,我不太明白“开始”是什么意思。我究竟做错了什么?谢谢你。
编辑:已经回答了我自己的问题......
解决方案
我不知道我可以从 onFragmentResult 中调用 getView()。
我需要做的就是实现通常会在 onFragmentResult 中的 onViewCreated 中出现的代码:
textView = getView().findViewById(R.id.vistaNoticiaText);
textView.setText(result);
推荐阅读
- deep-learning - 为更高维度的图像训练 GAN?
- javascript - 如何从页面上的共享布局中删除类?
- database - 在提交版本之前验证数据库状态的问题
- python - 从 Python 目录中读取所有图像并尝试将其存储在数组中
- oracle - 我正在尝试获取会员ID,发行书数最高和最低的人的会员姓名
- javascript - VueGoogleMaps 和 VueGoogleAutocomplete 组件在同一个 Vue 组件中无法正常工作
- python - 是否可以检查我的应用程序中所有 uwsgi 工作人员的内存使用情况(rss/vsz)?
- node.js - Angular 和 Fingerprintjs
- r - 格式化使用 ggdensity 生成的多个图的 R 降价输出
- html - 如何更改网格容器的行为方式?