Deepak Senapati
Deepak Senapati

Reputation: 1123

Get fragment object in activity while using viewPagerviewpager

Recently, I was trying to know How to swipe through fragments using a ViewPager. I have to set text on a TextView which is in Fragement from the activity. I found that one can get the Fragment object from ViewPager using :

getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":0");

When I tried to do this in onCreate() method of activity, it always returns null. I assume that is because Fragment is not started yet. Then in which method I should try to access the fragment object so that I can send arguments to the fragment methods?

Upvotes: 2

Views: 1879

Answers (2)

jazzbpn
jazzbpn

Reputation: 7348

This two answer SOLVE my problem.

ANSWER 1:

Fragment fragment = getSupportFragmentManager().getFragments().get(position);

OR ANSWER 2:

Fragment fragment = (Fragment) viewPager.getAdapter().
          instantiateItem(viewPager, viewPager.getCurrentItem());

Upvotes: 2

Michał Z.
Michał Z.

Reputation: 4119

If you have a ViewPager and you want to access to a fragment which is inside a ViewPager, you can use this code:

Fragment currentFragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem()); //gets current fragment
//now you have to cast it to your fragment, let's say it's name is SenapatiFragment

((SenapatiFragment)currentFragment).someMethod(...); // you have now access to public fields and methods that are inside your fragment

Upvotes: 1

Related Questions