问题
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.
my activity's 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" />
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 :/
回答1:
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.
回答2:
The ViewPager should have an FragmentAdapter associated with it. So you can do something like:
FragmentAdapter fa = (FragmentAdapter)viewPager.getAdapter();
Fragment f = fa.getItem(index);
回答3:
I did this: http://tamsler.blogspot.fr/2011/11/android-viewpager-and-fragments-part-ii.html
I'm not sure there is no better way to do it...
来源:https://stackoverflow.com/questions/13521830/call-a-method-on-a-fragment-in-a-viewpager