在ViewPager中的片段上调用方法 [英] call a method on a fragment in a ViewPager
问题描述
我要做的就是调用Fragment类的函数.但是我似乎找不到一种方法来访问ViewPager中的片段实例.
All I want to do is calling a function of my Fragment's class. But I can't seem to find a way to access the instance of my fragments which are in a ViewPager.
我的活动的xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
没有,所以我不能打电话给findFragmentById()(可以吗?) 我也不知道该给findFragmentByTag()什么,它总是返回null:/
There is no so I can't call findFragmentById() (can I?) also I don't know what to give to findFragmentByTag(), it always return null :/
推荐答案
pagerAdapter.getItem(int)方法通常会创建该片段的新实例,因此,您可以使用HashMap来存储对已经存在的片段.
The pagerAdapter.getItem(int) method usually creates a new instance of the fragment, however, so what you can do is use a HashMap to store a reference to the already existing fragments.
// ViewPagerAdapter
private HashMap<Integer, Fragment> fragmentHashMap = new HashMap<>();
@Override
public Fragment getItem(int position) {
if (fragmentHashMap.get(position) != null) {
return fragmentHashMap.get(position);
}
TabFragment tabFragment = new TabFragment();
fragmentHashMap.put(position, tabFragment);
return tabFragment;
}
然后,您可以找到片段来调用其方法:
Then you can find your fragment to call its methods:
FragmentAdapter fa = (FragmentAdapter)viewPager.getAdapter();
TabFragment theFragment = (TabFragment)fa.getItem(index);
theFragment.customMethod(Object obj);
您将必须跟踪哪个片段与哪个索引一起使用,因为将它们强制转换为它们的特定类才能访问它们的方法.
You will have to keep track of which fragment goes with which index because you cast them to their specific class in order to access their methods.
这篇关于在ViewPager中的片段上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!