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 :/
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With