How to know if a Fragment is Visible?

前端 未结 10 1904
闹比i
闹比i 2020-12-01 06:07

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? Th

相关标签:
10条回答
  • 2020-12-01 06:22

    Try this if you have only one Fragment

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                        //TODO: Your Code Here
                    }
    
    
    0 讨论(0)
  • 2020-12-01 06:24

    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");
    }
    
    0 讨论(0)
  • 2020-12-01 06:25
    ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);
    
        if (articleFrag != null && articleFrag.isVisible()) {
    
            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        }
    

    see http://developer.android.com/training/basics/fragments/communicating.html

    0 讨论(0)
  • 2020-12-01 06:26

    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.

    NOTICE: getUserVisibleHint() is now deprecated. be careful.

    0 讨论(0)
  • 2020-12-01 06:27

    You should be able to do the following:

    MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
    if (test != null && test.isVisible()) {
         //DO STUFF
    }
    else {
        //Whatever
    }
    
    0 讨论(0)
  • 2020-12-01 06:32

    You can override setMenuVisibility like this:

    @Override
    public void setMenuVisibility(final boolean visible) {
       if (visible) {
          //Do your stuff here
       }
    
       super.setMenuVisibility(visible);
    }
    
    0 讨论(0)
提交回复
热议问题