Java 通过setFragmentResult将信息发送到另一个片段
我试图将来自片段A的recyclerView的OnClickListener的信息发送到新创建的片段B,并将其显示在文本视图中。我遵循android关于片段到片段通信的文档,其中说我应该使用片段结果API: 片段A的RecyclerView.Adapter的OnClickListener的代码:Java 通过setFragmentResult将信息发送到另一个片段,java,android-studio,android-fragments,Java,Android Studio,Android Fragments,我试图将来自片段A的recyclerView的OnClickListener的信息发送到新创建的片段B,并将其显示在文本视图中。我遵循android关于片段到片段通信的文档,其中说我应该使用片段结果API: 片段A的RecyclerView.Adapter的OnClickListener的代码: @Override public void onBindViewHolder(@NonNull NoticiaViewHolder holder, int position) {
@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
当我在片段A的recyclerView中单击一个项目时,片段B被创建并成功加载。但是,正如您所看到的,onFragmentResult中的代码似乎在onViewCreated之后运行,这意味着我无法访问捆绑包的内容以在片段B的textView中显示它。我注意到文件上说:
“片段A随后接收结果,并在片段启动后执行侦听器回调。”
然而,我不太明白“开始”是什么意思。我做错了什么?多谢各位
编辑:已经回答了我自己的问题…我不知道我可以从onFragmentResult中调用getView() 我所需要做的就是实现通常在onFragmentResult中创建的OnView中的代码:
textView = getView().findViewById(R.id.vistaNoticiaText);
textView.setText(result);