I know there are lots of similar questions in StackOverflow but my question is little different.
I have nested hierarchy of Fragments like in below structure:
<
We can easily map which fragment is now visible using mViewPager.getCurrentItem()
method. This method gives int
value number from which we can find the current fragment.
-- For access and get this method result we have two options:
Static
viewPager instance in activity and use wherever we
wantviewPager
instance in fragment (findViewById()
)and using one from above two methods getCurrentItem()
in fragment to find which fragment is visible now.
For example,
public static ViewPager mViewPager;
MainActivity.mViewPager.getCurrentItem()
to get current fragmentAlso, method that shows which fragment is visible:
public void whichIsVisible() {
String msg = "";
int curFragNo = MainActivity.mViewPager.getCurrentItem();
switch (curFragNo) {
case 0:
msg = "AFragment is visible.";
break;
case 1:
msg = "BFragment is visible.";
break;
case 2:
msg = "CFragment is visible.";
break;
case 3:
msg = "DFragment is visible.";
break;
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
(2) For non-static use,
viewPager
instance in fragment by below code,viewPager=(ViewPager) view.getRootView().findViewById(R.id.container);
and then
viewPager.getCurrentItem()
to get index and find current visible fragment as per use.