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:
Activity | | AFragment | (ViewPager) | | | | BFragment BFragment ..... | (ViewPager) | | | | CFragment CFragment ... | (ViewPager) | | | | DFragment DFragment ...
Now i want to know that whether DFragment
is showing to user or not?
I tried lots of solution from StackOverflow but couldn't get sucess.
What i tried is:
I tried setUserVisibleHint()
but it returns true
for multiple DFragment
in above hierarchy which is a cause of ViewPager
I also tried from these links: link1, link2, link3 and so on... but did not got actual solution.
Waiting for help. Thank you.
UPDATE
Adapter Class
class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } }
Adding some information here that I experienced: fragment. isVisible is only working ( true/false ) when you replaceFragment() otherwise if you work with addFragment() , isVisible always returns true whether the fragment is in behind of some other fragment.
Since all fragments are destroyed if the activity is destroyed, a simple answer could be calling getActivity(). isDestroyed() returning true if the activity is destroyed, therefore the fragment is destroyed.
onStart()The onStart() method is called once the fragment gets visible.
This method allows you to retrieve the instance of a previously added fragment with the given tag regardless of the container it was added to.
You can check, whether the View
that fragment inflated is visible on the device's screen:
Fragment fragment = ... // retrieve from `ViewPager`'s adapter. View fragmentRootView = fragment.getView(); if (fragmentRootView != null && fragmentRootView.getGlobalVisibleRect(new Rect())) { // fragment is visible } else { // fragment is not visible }
getGlobalVisibleRect()
will return true
if part of the view is visible at the root level.
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