How to know if a Fragment is Visible?

2019-01-11 16:17发布

I'm using the support library v4 and my questions are, How to know if a Fragment is Visible? and How can I change the propierties of the Layout inflated in the Fragment? Thanks in advance.

---Edit---

I'm using fragments like in the android developers tutorial with a FragmentActivity

8条回答
姐就是有狂的资本
2楼-- · 2019-01-11 16:24

Both isVisible() and isAdded() return true as soon as the Fragment is created, and not even actually visible. The only solution that actually works is:

if (isAdded() && isVisible() && getUserVisibleHint()) {
    ... do your thing
}

This does the job. Period.

查看更多
Evening l夕情丶
3楼-- · 2019-01-11 16:25

You can override setMenuVisibility like this:

@Override
public void setMenuVisibility(final boolean visible) {
   if (visible) {
      //Do your stuff here
   }

   super.setMenuVisibility(visible);
}
查看更多
欢心
4楼-- · 2019-01-11 16:37

You should be able to do the following:

MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
     //DO STUFF
}
else {
    //Whatever
}
查看更多
欢心
5楼-- · 2019-01-11 16:37

If you want to know when use is looking at the fragment you should use

yourFragment.isResumed()

instead of

yourFragment.isVisible()

First of all isVisible() already checks for isAdded() so no need for calling both. Second, non-of these two means that user is actually seeing your fragment. Only isResumed() makes sure that your fragment is in front of the user and user can interact with it if thats whats you are looking for.

查看更多
在下西门庆
6楼-- · 2019-01-11 16:38

you can try this way:

Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);

or

Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);

In this if, you check if currentFragment is instance of YourFragment

if (currentFragment instanceof YourFragment) {
     Log.v(TAG, "your Fragment is Visible");
}
查看更多
Explosion°爆炸
7楼-- · 2019-01-11 16:40

getUserVisibleHint() comes as true only when the fragment is on the view and visible

查看更多
登录 后发表回答