我有一个带有 ViewPager 的 fragment 。 ViewPager 内的每个 fragment 都会显示一些基于主 fragment 中的 SearchBar 的数据。主 Fragment 还有一个名为 getKeyword()
的公共(public)方法(返回 SearchBar 的字符串)。但我不知道如何获取 ViewPager fragment 内主 fragment 的引用。
我尝试使用 onAttach()
方法来获取引用,但它返回了 mainActivity
的引用。
我还尝试使用getChildFragmentManager()
来获取主Fragment,但我不知道主Fragment的id是什么(主Fragment实际上是来自另一个ViewPager的Fragment)。
最佳答案
fragment 之间通信的更好方法是使用回调接口(interface),
- 您在包含搜索栏文本的 fragment 上创建界面
- 然后在 Activity 上实现该接口(interface)
- 在包含搜索文本并创建接口(interface)的 fragment 的 onAttach 方法上,您创建接口(interface)回调的实例并将其填充,将 Activity 强制转换为回调实例
公共(public)类 MainFragment 扩展 Fragment {
//all your other stuff
private MyFragment.Callback myCallback;
public void onAttach(Activity activity) {
super.onAttach(activity);
if( activity instanceOf MyFragment.Callback ) {
myCallback = (MyFragment.Callback) activity;
} else {
/*here you manage the case when the activity does not have the interface callback implemented*/
//Generally with this
throws new ClassCastException(
activity.class.getSimpleName() +
" should implement " +
MyFragment.class.getSimpleName()
);
}
}
private void thisMethodIsUsedWhenTheSearchIsExecuted(String searchText) {
//here you get the string of the search however you need
myCallback.callWhenSearch(searchText);
}
public interface Callback {
void callWhenSearch(String searchText);
}
}
这是管理 fragment 的 Activity 的代码
public class MyActivity extends AppCompatActivity implements MyFragment.Callback {
// anything you need for the main activity
public void callWhenSearch(String searchText) {
//searchText will contain the text of the search executed on MyFragment
//and here you can execute a method that calls the fragment where you need to see the result of your search for example
instanceOfSecondFragment.visualizeResultsOf(searchText)
}
}
您可以在这里获取一些官方文档:
Communicating with Other Fragments
如果您需要更多帮助,请告诉我。
关于java - ViewPager 中 fragment 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44556013/