判断当前Fragment是否切换到前台

我们都知道,Activity有onResume()方法,可以很方便程序员在该Activity(重新)展示在用户面前的时候,执行一些数据更新的操作,例如需要重新加载网络数据。那么Fragment呢,查看Fragment源码,可以知道,类似的方法是:

// Hint provided by the app that this fragment is currently visible to the user.
    boolean mUserVisibleHint = true;


/**
     * Set a hint to the system about whether this fragment's UI is currently visible
     * to the user. This hint defaults to true and is persistent across fragment instance
     * state save and restore.
     *
     * 

An app may set this to false to indicate that the fragment's UI is * scrolled out of visibility or is otherwise not directly visible to the user. * This may be used by the system to prioritize operations such as fragment lifecycle updates * or loader ordering behavior.

* * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default), * false if it is not. */ public void setUserVisibleHint(boolean isVisibleToUser) { if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) { mFragmentManager.performPendingDeferredStart(this); } mUserVisibleHint = isVisibleToUser; mDeferStart = !isVisibleToUser; }

变量mUserVisibleHint表示当前Fragment是否对用户可见,true为可见,false为不可见。setUserVisibleHint()方法在每次切换Fragment的时候都会被调用,那么,我们只要重写该方法,并添加相应的更新代码即可(注意不要在主线程更新UI)。

你可能感兴趣的:(Android)