1. 程式人生 > >Android - 解決Fragment + ViewPager的生命週期問題

Android - 解決Fragment + ViewPager的生命週期問題

public class FragmentVisibleHelper implements LifecycleObserver {

    private static final String TAG = "VisibleHelper";

    public interface IVisibleListener {

        void onVisible();

        void onInVisible();
    }

    boolean mIsVisibleToUser;
    boolean mStarted = false;

    volatile
boolean mIsCalledVisible = false; volatile boolean mIsCalledInvisible = false; IVisibleListener mListener; public void setListener(IVisibleListener mListener) { this.mListener = mListener; } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void onResume() { Log.
d(TAG, String.format("%-60s %s", this.toString(), "onResume() called:")); if (mIsVisibleToUser) { dispatchVisible(); } } private void dispatchVisible() { Log.d(TAG, String.format("%-60s %s", this.toString(), "dispatchVisible() called mIsCalledVisible = [" +
mIsCalledVisible + "] mIsCalledInvisible = [" + mIsCalledInvisible + "] ")); if (!mIsCalledVisible) { mIsCalledVisible = true; mIsCalledInvisible = false; if (Profile.LOG) { Log.d(TAG, String.format("%-60s %s", this.toString(), "dispatchVisible() called onVisible")); } if (mListener != null) { mListener.onVisible(); } } } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void onPause() { Log.d(TAG, String.format("%-60s %s", this.toString(), "onPause() called:")); if (mIsVisibleToUser) { dispatchInvisible(); } } private void dispatchInvisible() { Log.d(TAG, String.format("%-60s %s", this.toString(), "dispatchInvisible() called mIsCalledVisible = [" + mIsCalledVisible + "] mIsCalledInvisible = [" + mIsCalledInvisible + "] ")); if (!mIsCalledInvisible) { mIsCalledInvisible = true; mIsCalledVisible = false; if (Profile.LOG) { Log.d(TAG, String.format("%-60s %s", this.toString(), "dispatchInvisible() called onInVisible")); } if (mListener != null) { mListener.onInVisible(); } } } @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart() { Log.d(TAG, String.format("%-60s %s", this.toString(), "onStart() called")); mStarted = true; if (mIsVisibleToUser) { dispatchVisible(); } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() { Log.d(TAG, String.format("%-60s %s", this.toString(), "onStop() called")); if (mIsVisibleToUser) { dispatchInvisible(); } mStarted = false; } public void setUserVisibleHint(boolean isVisibleToUser) { Log.d(TAG, String.format("%-60s %s", this.toString(), "setUserVisibleHint() called with: isVisibleToUser = [" + isVisibleToUser + "]:")); mIsVisibleToUser = isVisibleToUser; if (mStarted) { // fragment have created if (mIsVisibleToUser) { dispatchVisible(); } else { dispatchInvisible(); } } } public boolean isVisibleToUser() { return mIsVisibleToUser; } }