現在のFragmentがフロントに切り替えられているかどうかを判断
2401 ワード
ActivityにはonResume()メソッドがあり、プログラマがこのActivity(再)をユーザーの前に表示するときに、ネットワークデータの再ロードなどのデータ更新操作を実行するのに便利であることはよく知られています.では、Fragmentは、Fragmentのソースコードを見てみると、似たような方法がわかります.
変数mUserVisibleHintは、現在のFragmentがユーザーに対して表示されているかどうか、trueが表示されているかどうか、falseが非表示であることを示します.setuUserVisibleHint()メソッドはFragmentを切り替えるたびに呼び出されるので、このメソッドを書き換え、対応する更新コードを追加すればよい(メインスレッドでUIを更新しないように注意).
// 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が非表示であることを示します.setuUserVisibleHint()メソッドはFragmentを切り替えるたびに呼び出されるので、このメソッドを書き換え、対応する更新コードを追加すればよい(メインスレッドでUIを更新しないように注意).