Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a method on a fragment in a 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.

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 :/

like image 233
foke Avatar asked Dec 06 '22 10:12

foke


2 Answers

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.

like image 148
Michael Fulton Avatar answered Dec 20 '22 06:12

Michael Fulton


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);
like image 37
Neil Avatar answered Dec 20 '22 06:12

Neil