91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

解決androidx下的fragment的lazy懶加載問題

發布時間:2020-08-03 11:14:59 來源:億速云 閱讀:672 作者:小豬 欄目:移動開發

小編這次要給大家分享的是解決androidx下的fragment的lazy懶加載問題,文章內容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

一、前置準備工作

幾個關于androidx的fragment懶加載方案,都離不開如下幾個包:

  • androidx.fragment:fragment:1.1.0-alpha07 以上,支持setMaxLifecycle方法即可
  • androidx.viewpager:viewpager:1.0.0 以上,如果涉及到viewpager內的fragment使用

我在實際測試代碼中使用了如下版本,可供參考:

  • androidx.fragment:fragment:1.2.4
  • androidx.viewpager:viewpager:1.0.0
  • FlycoTabLayout

還準備了4個Activity與5個Fragment:

  • AddShowHideFragmentActivity 通過add show顯示的案例
  • AddShowHideFragmentInFragmentActivity 嵌套在fragment中的,通過add show顯示的fragment案例
  • ViewPagerFragmentActivity 通過ViewPager滑動顯示的案例
  • ViewPagerFragmentInFragmentActivity 嵌套在fragment中的,通過ViewPager滑動顯示的案例
  • AddFragmentInFragment 操作add show的fragment
  • ViewPagerFragmentInFragment 操作ViewPager的fragment
  • BlankFragment1 打印生命周期日志的空頁面1
  • BlankFragment2 打印生命周期日志的空頁面2
  • BlankFragment3 打印生命周期日志的空頁面3

相應的幾個簡單布局文件:

文件:fragment_main.xml

加載ViewPager控件和AddShow使用的FrameLayout,以及測試跳轉后返回的TextView按鈕。

fragment_main.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  >

  <androidx.viewpager.widget.ViewPager
    android:id="@+id/vp_fragment"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

  <com.flyco.tablayout.CommonTabLayout
    android:id="@+id/tab_title"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/colorPrimary"
    app:tl_indicator_color="@color/colorAccent"
    app:tl_indicator_height="2dp"
    app:tl_indicator_width="30dp"
    app:tl_tab_space_equal="true"
    app:tl_textBold="SELECT"
    app:tl_textSelectColor="#000000"
    app:tl_textUnselectColor="#333333"
    app:layout_constraintTop_toBottomOf="@id/vp_fragment"
    app:layout_constraintLeft_toLeftOf="parent"
    />

  <FrameLayout
    android:id="@+id/fl_in_content"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:layout_constraintTop_toBottomOf="@id/tab_title"
    />

  <TextView
    android:id="@+id/tv_next"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="next"
    android:gravity="center"
    app:layout_constraintBottom_toBottomOf="parent"
    />

</androidx.constraintlayout.widget.ConstraintLayout>

文件:activity_lazy_fragment.xml

這里是測試fragment嵌套情況下的布局,fl_content用來加載fragment

activity_lazy_fragment.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".lazyFragment.ViewPagerFragmentActivity">

  <FrameLayout
    android:id="@+id/fl_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    />

</androidx.constraintlayout.widget.ConstraintLayout>

文件:fragment_blank.xml

這一個空fragment就沒什么講究了

fragment_blank.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  >

  <TextView
    android:id="@+id/tv_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="" />

</FrameLayout>

二、具體代碼分析

1) ViewPager+Fragment

最常見的使用方式,由ViewPager滑動顯示多個Fragment,直接上代碼:

activity頁面代碼

其中就是個簡單的viewpager設置adapter然后加載fragment集合顯示

/**
 * viewpager內的fragment懶加載
 */
public class ViewPagerFragmentActivity extends BindActivity implements BlankFragment1.OnFragmentInteractionListener , BlankFragment2.OnFragmentInteractionListener, BlankFragment3.OnFragmentInteractionListener {

  private static final String KEY_FRAGMENT_1 = "1";
  private static final String KEY_FRAGMENT_2 = "2";
  private static final String KEY_FRAGMENT_3 = "3";
  @BindView(R.id.vp_fragment)
  ViewPager vp;
  @BindView(R.id.tv_next)
  TextView tv_next;
  BlankFragment1 blankFragment1;
  BlankFragment2 blankFragment2;
  BlankFragment3 blankFragment3;
  List<Fragment> fragmentList;
  @Override
  protected int setLayoutID() {
    return R.layout.fragment_main;
  }

  @Override
  protected void initViews(Bundle savedInstanceState) {

    tv_next.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent=new Intent(mContext, MMKVActivity.class);
        startActivity(intent);
      }
    });

    if(savedInstanceState != null){
      blankFragment1 = (BlankFragment1)getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_1);
      blankFragment2 = (BlankFragment2)getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_2);
      blankFragment3 = (BlankFragment3)getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_3);
    }

    fragmentList=new ArrayList<>();
    if (blankFragment1==null){
      fragmentList.add(blankFragment1=BlankFragment1.newInstance("11111",""));
    }else {
      fragmentList.add(blankFragment1);
    }
    if (blankFragment2==null){
      fragmentList.add(blankFragment2=BlankFragment2.newInstance("22222",""));
    }else {
      fragmentList.add(blankFragment2);
    }
    if (blankFragment3==null){
      fragmentList.add(blankFragment3=BlankFragment3.newInstance("333333",""));
    }else {
      fragmentList.add(blankFragment3);
    }

    vp.setAdapter(new BaseFragmentXPagerAdapter(getSupportFragmentManager(),fragmentList,null));

  }

  @Override
  public void onFragmentInteraction(Uri uri) {
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    if(blankFragment1 != null&&blankFragment1.isAdded()) {
      getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_1,blankFragment1);
    }
    if(blankFragment2 != null&&blankFragment2.isAdded()){
      getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_2,blankFragment2);
    }
    if(blankFragment3 != null&&blankFragment3.isAdded()){
      getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_3,blankFragment3);
    }
    super.onSaveInstanceState(outState);
  }
}

BaseFragmentXPagerAdapter頁面代碼

新版FragmentPagerAdapter多了2個常量

@Retention(RetentionPolicy.SOURCE)
  @IntDef({BEHAVIOR_SET_USER_VISIBLE_HINT, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT})
  private @interface Behavior { }

用在了構造方法中

/**
   * Constructor for {@link FragmentPagerAdapter}.
   *
   * If {@link #BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT} is passed in, then only the current
   * Fragment is in the {@link Lifecycle.State#RESUMED} state. All other fragments are capped at
   * {@link Lifecycle.State#STARTED}. If {@link #BEHAVIOR_SET_USER_VISIBLE_HINT} is passed, all
   * fragments are in the {@link Lifecycle.State#RESUMED} state and there will be callbacks to
   * {@link Fragment#setUserVisibleHint(boolean)}.
   *
   * @param fm fragment manager that will interact with this adapter
   * @param behavior determines if only current fragments are in a resumed state
   */
  public FragmentPagerAdapter(@NonNull FragmentManager fm,
      @Behavior int behavior) {
    mFragmentManager = fm;
    mBehavior = behavior;
  }

我們只需要在構造adapter時,使用BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT這個常量就行

/**
 * support lazy init
 */
public class BaseFragmentXPagerAdapter extends FragmentPagerAdapter {

  private List<Fragment> mFragmentList = new ArrayList<>();
  private List<String> mFragmentTitleList = new ArrayList<>();

  public BaseFragmentXPagerAdapter(@NonNull FragmentManager fm,List<Fragment> fragmentList,List<String> fragmentTitleList) {
    this(fm,fragmentList,fragmentTitleList,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
  }
  public BaseFragmentXPagerAdapter(@NonNull FragmentManager fm,List<Fragment> fragmentList,List<String> fragmentTitleList, int behavior) {
    super(fm, behavior);
    if (fragmentList!=null){
      mFragmentList.addAll(fragmentList);
    }
    if (fragmentTitleList!=null){
      mFragmentTitleList.addAll(fragmentTitleList);
    }
  }

  public BaseFragmentXPagerAdapter(@NonNull FragmentManager fm,Fragment[] fragmentList,String[] fragmentTitleList) {
    this(fm,fragmentList,fragmentTitleList,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
  }
  public BaseFragmentXPagerAdapter(@NonNull FragmentManager fm,Fragment[] fragmentList,String[] fragmentTitleList, int behavior) {
    super(fm, behavior);
    if (fragmentList!=null){
      for (int i = 0; i < fragmentList.length; i++) {
        mFragmentList.add(fragmentList[i]);
      }
    }
    if (fragmentTitleList!=null){
      for (int i = 0; i < fragmentTitleList.length; i++) {
        mFragmentTitleList.add(fragmentTitleList[i]);
      }
    }
  }

  @NonNull
  @Override
  public Fragment getItem(int position) {
    if (mFragmentList!=null&&!mFragmentList.isEmpty()){
      return mFragmentList.get(position);
    }else {
      return null;
    }
  }

  @Override
  public int getCount() {
    if (mFragmentList!=null&&!mFragmentList.isEmpty()){
      return mFragmentList.size();
    }else {
      return 0;
    }
  }

  @Nullable
  @Override
  public CharSequence getPageTitle(int position) {
    if (mFragmentTitleList!=null&&!mFragmentTitleList.isEmpty()&&position<mFragmentTitleList.size()){
      return mFragmentTitleList.get(position);
    }else {
      return null;
    }
  }
}

最終打印生命周期日志,確認結果,viewPager+fragment搭配pagerAdapter的behavior在各種情況下的日志,可以看出新版viewPager+pagerAdapter實測下來,Fragment的onResume生命周期只會在當前頁顯示時調用

首次進入 顯示第一頁
ViewPagerFragmentActivity--->onCreate
ViewPagerFragmentActivity--->onStart
ViewPagerFragmentActivity--->onResume
BlankFragment1--->onAttach
BlankFragment1--->onCreate
BlankFragment2--->onAttach
BlankFragment2--->onCreate
BlankFragment1--->onViewCreated
BlankFragment1--->onActivityCreated
BlankFragment1--->onStart
BlankFragment2--->onViewCreated
BlankFragment2--->onActivityCreated
BlankFragment2--->onStart
BlankFragment1--->onResume <<=================== 當前頁

滑動到第二頁
BlankFragment3--->onAttach
BlankFragment3--->onCreate
BlankFragment3--->onViewCreated
BlankFragment3--->onActivityCreated
BlankFragment3--->onStart
BlankFragment1--->onPause
BlankFragment2--->onResume <<=================== 當前頁

鎖屏
BlankFragment2--->onPause
ViewPagerFragmentActivity--->onPause
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentActivity--->onStop
ViewPagerFragmentActivity--->onSaveInstanceState

解鎖屏幕
ViewPagerFragmentActivity--->onRestart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentActivity--->onStart
ViewPagerFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當前頁

HOME回到桌面
BlankFragment2--->onPause
ViewPagerFragmentActivity--->onPause
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentActivity--->onStop
ViewPagerFragmentActivity--->onSaveInstanceState

返回app頁面
ViewPagerFragmentActivity--->onRestart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentActivity--->onStart
ViewPagerFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當前頁

跳轉新頁面
BlankFragment2--->onPause
ViewPagerFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentActivity--->onStop
ViewPagerFragmentActivity--->onSaveInstanceState

返回ViewPager的頁面
MMKVActivity--->onPause
ViewPagerFragmentActivity--->onRestart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentActivity--->onStart
ViewPagerFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當前頁
MMKVActivity--->onStop
MMKVActivity--->onDestroy

2) Fragment嵌套Fragment內的ViewPager+Fragment

外層的activity只是add一個fragment

/**
 * fragment內的viewpager內的fragment懶加載
 */
public class ViewPagerFragmentInFragmentActivity extends BindActivity implements ViewPagerFragmentInFragment.OnFragmentInteractionListener ,BlankFragment1.OnFragmentInteractionListener, BlankFragment2.OnFragmentInteractionListener, BlankFragment3.OnFragmentInteractionListener {

  @Override
  protected int setLayoutID() {
    return R.layout.activity_lazy_fragment;
  }

  @Override
  protected void initViews(Bundle savedInstanceState) {
    FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.fl_content, ViewPagerFragmentInFragment.newInstance("",""));
    transaction.commit();
  }

  @Override
  public void onFragmentInteraction(Uri uri) {

  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
  }
}

嵌套用的fragment類,ViewPagerFragmentInFragment

/**
 * viewpager在一個fragment內
 */
public class ViewPagerFragmentInFragment extends BaseFragment {
  private static final String ARG_PARAM1 = "param1";
  private static final String ARG_PARAM2 = "param2";

  private String mParam1;
  private String mParam2;

  private OnFragmentInteractionListener mListener;

  private static final String KEY_FRAGMENT_1 = "1";
  private static final String KEY_FRAGMENT_2 = "2";
  private static final String KEY_FRAGMENT_3 = "3";

  @BindView(R.id.vp_fragment)
  ViewPager vp;
  @BindView(R.id.tv_next)
  TextView tv_next;
  BlankFragment1 blankFragment1;
  BlankFragment2 blankFragment2;
  BlankFragment3 blankFragment3;
  List<Fragment> fragmentList;

  public ViewPagerFragmentInFragment() {
  }

  public static ViewPagerFragmentInFragment newInstance(String param1, String param2) {
    ViewPagerFragmentInFragment fragment = new ViewPagerFragmentInFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
  }

  @Override
  public void onSaveInstanceState(@NonNull Bundle outState) {

    if(blankFragment1 != null&&blankFragment1.isAdded()) {
      mActivity.getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_1,blankFragment1);
    }
    if(blankFragment2 != null&&blankFragment2.isAdded()){
      mActivity.getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_2,blankFragment2);
    }
    if(blankFragment3 != null&&blankFragment3.isAdded()){
      mActivity.getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_3,blankFragment3);
    }
    super.onSaveInstanceState(outState);
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      mParam1 = getArguments().getString(ARG_PARAM1);
      mParam2 = getArguments().getString(ARG_PARAM2);
    }

  }

  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    tv_next.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent=new Intent(mContext, MMKVActivity.class);
        startActivity(intent);
      }
    });

    if(savedInstanceState != null){
      blankFragment1 = (BlankFragment1)mActivity.getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_1);
      blankFragment2 = (BlankFragment2)mActivity.getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_2);
      blankFragment3 = (BlankFragment3)mActivity.getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_3);
    }

    fragmentList=new ArrayList<>();
    if (blankFragment1==null){
      fragmentList.add(blankFragment1=BlankFragment1.newInstance("11111",""));
    }else {
      fragmentList.add(blankFragment1);
    }
    if (blankFragment2==null){
      fragmentList.add(blankFragment2=BlankFragment2.newInstance("22222",""));
    }else {
      fragmentList.add(blankFragment2);
    }
    if (blankFragment3==null){
      fragmentList.add(blankFragment3=BlankFragment3.newInstance("333333",""));
    }else {
      fragmentList.add(blankFragment3);
    }

    vp.setAdapter(new BaseFragmentXPagerAdapter(mActivity.getSupportFragmentManager(),fragmentList,null));

  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_main, container, false);
  }

  public void onButtonPressed(Uri uri) {
    if (mListener != null) {
      mListener.onFragmentInteraction(uri);
    }
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
      mListener = (OnFragmentInteractionListener) context;
    } else {
      throw new RuntimeException(context.toString()
          + " must implement OnFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  public interface OnFragmentInteractionListener {
    void onFragmentInteraction(Uri uri);
  }
}

實測日志可以發現,哪怕fragment是嵌套過的,Fragment的onResume生命周期也只會在當前頁顯示時調用:

首次進入顯示第一頁
ViewPagerFragmentInFragment--->onStart
ViewPagerFragmentInFragmentActivity--->onStart
ViewPagerFragmentInFragmentActivity--->onResume
ViewPagerFragmentInFragment--->onResume
BlankFragment1--->onAttach
BlankFragment1--->onCreate
BlankFragment2--->onAttach
BlankFragment2--->onCreate
BlankFragment1--->onViewCreated
BlankFragment1--->onActivityCreated
BlankFragment1--->onStart
BlankFragment2--->onViewCreated
BlankFragment2--->onActivityCreated
BlankFragment2--->onStart
BlankFragment1--->onResume <<=================== 當前頁

滑動到第二頁
BlankFragment3--->onAttach
BlankFragment3--->onCreate
BlankFragment3--->onViewCreated
BlankFragment3--->onActivityCreated
BlankFragment3--->onStart
BlankFragment1--->onPause
BlankFragment2--->onResume <<=================== 當前頁

鎖屏
ViewPagerFragmentInFragment--->onPause
BlankFragment2--->onPause
ViewPagerFragmentInFragmentActivity--->onPause
ViewPagerFragmentInFragment--->onStop
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentInFragmentActivity--->onStop
ViewPagerFragmentInFragmentActivity--->onSaveInstanceState

解鎖屏幕
ViewPagerFragmentInFragmentActivity--->onRestart
ViewPagerFragmentInFragment--->onStart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentInFragmentActivity--->onStart
ViewPagerFragmentInFragmentActivity--->onResume
ViewPagerFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當前頁

HOME回到桌面
ViewPagerFragmentInFragment--->onPause
BlankFragment2--->onPause
ViewPagerFragmentInFragmentActivity--->onPause
ViewPagerFragmentInFragment--->onStop
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentInFragmentActivity--->onStop
ViewPagerFragmentInFragmentActivity--->onSaveInstanceState

返回app頁面
ViewPagerFragmentInFragmentActivity--->onRestart
ViewPagerFragmentInFragment--->onStart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentInFragmentActivity--->onStart
ViewPagerFragmentInFragmentActivity--->onResume
ViewPagerFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當前頁

跳轉新頁面
ViewPagerFragmentInFragment--->onPause
BlankFragment2--->onPause
ViewPagerFragmentInFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
ViewPagerFragmentInFragment--->onStop
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentInFragmentActivity--->onStop
ViewPagerFragmentInFragmentActivity--->onSaveInstanceState

返回ViewPager的頁面
MMKVActivity--->onPause
ViewPagerFragmentInFragmentActivity--->onRestart
ViewPagerFragmentInFragment--->onStart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentInFragmentActivity--->onStart
ViewPagerFragmentInFragmentActivity--->onResume
ViewPagerFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當前頁

3) 通過add show hide操作多個fragment

activity代碼中的一個細節為通過add show的頁面,設置transaction.setMaxLifecycle(fragment, Lifecycle.State.RESUMED),讓該fragment的生命周期能順利走到resume;

通過hide隱藏的頁面,設置transaction.setMaxLifecycle(fragmentList.get(i), Lifecycle.State.CREATED),使隱藏了的fragment生命周期只能走到創建階段,無法走到resume方法。

/**
 * add show hide下的fragment懶加載
 */
public class AddShowHideFragmentActivity extends BindActivity implements BlankFragment1.OnFragmentInteractionListener , BlankFragment2.OnFragmentInteractionListener, BlankFragment3.OnFragmentInteractionListener {

  private static final String KEY_FRAGMENT_1 = "1";
  private static final String KEY_FRAGMENT_2 = "2";
  private static final String KEY_FRAGMENT_3 = "3";
  @BindView(R.id.tab_title)
  CommonTabLayout commonTabLayout;
  @BindView(R.id.tv_next)
  TextView tv_next;
  BlankFragment1 blankFragment1;
  BlankFragment2 blankFragment2;
  BlankFragment3 blankFragment3;
  List<Fragment> fragmentList;
  @Override
  protected int setLayoutID() {
    return R.layout.fragment_main;
  }

  @Override
  protected void initViews(Bundle savedInstanceState) {
    tv_next.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent=new Intent(mContext, MMKVActivity.class);
        startActivity(intent);
      }
    });
    if(savedInstanceState != null){
      blankFragment1 = (BlankFragment1)getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_1);
      blankFragment2 = (BlankFragment2)getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_2);
      blankFragment3 = (BlankFragment3)getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_3);
    }
    fragmentList=new ArrayList<>();
    if (blankFragment1==null){
      fragmentList.add(blankFragment1=BlankFragment1.newInstance("11111",""));
    }else {
      fragmentList.add(blankFragment1);
    }
    if (blankFragment2==null){
      fragmentList.add(blankFragment2=BlankFragment2.newInstance("22222",""));
    }else {
      fragmentList.add(blankFragment2);
    }
    if (blankFragment3==null){
      fragmentList.add(blankFragment3=BlankFragment3.newInstance("33333",""));
    }else {
      fragmentList.add(blankFragment3);
    }
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    tabEntities.add(new TabLayoutEntity("商品1"));
    tabEntities.add(new TabLayoutEntity("評價2"));
    tabEntities.add(new TabLayoutEntity("詳情3"));
    commonTabLayout.setTabData(tabEntities);
    commonTabLayout.setCurrentTab(0);
    showFragment(fragmentList.get(0),false);
    commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override
      public void onTabSelect(int position) {
        showFragment(fragmentList.get(position),false);
      }

      @Override
      public void onTabReselect(int position) {
        showFragment(fragmentList.get(position),false);
      }
    });

  }

  private void showFragment(Fragment fragment,boolean replace){
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    if (replace){
      transaction.replace(R.id.fl_in_content,fragment);
    }else {
      if (!fragment.isAdded()){
        transaction.add(R.id.fl_in_content,fragment,fragment.getClass().getSimpleName());
      }
      hideAllFragment(transaction,fragment);
      transaction.show(fragment);
      transaction.setMaxLifecycle(fragment, Lifecycle.State.RESUMED);
    }
    transaction.commit();
  }
  private void hideAllFragment(FragmentTransaction transaction,Fragment withoutFragment){
    for (int i = 0; i < fragmentList.size(); i++) {
      if (!fragmentList.get(i).equals(withoutFragment)&&fragmentList.get(i).isAdded()){
        transaction.hide(fragmentList.get(i));
        transaction.setMaxLifecycle(fragmentList.get(i), Lifecycle.State.CREATED);
      }
    }
  }

  @Override
  public void onFragmentInteraction(Uri uri) {
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    if(blankFragment1 != null&&blankFragment1.isAdded()) {
      getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_1,blankFragment1);
    }
    if(blankFragment2 != null&&blankFragment2.isAdded()){
      getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_2,blankFragment2);
    }
    if(blankFragment3 != null&&blankFragment3.isAdded()){
      getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_3,blankFragment3);
    }
    super.onSaveInstanceState(outState);
  }
}

首次進入 顯示第一頁
AddShowHideFragmentActivity--->onCreate
BlankFragment1--->onAttach
BlankFragment1--->onCreate
BlankFragment1--->onViewCreated
BlankFragment1--->onActivityCreated
BlankFragment1--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment1--->onResume <<=================== 當前頁

點擊顯示第二頁
BlankFragment2--->onAttach
BlankFragment2--->onCreate
BlankFragment1--->onHiddenChanged=true
BlankFragment1--->onPause
BlankFragment1--->onStop
BlankFragment1--->onDestroyView
BlankFragment2--->onViewCreated
BlankFragment2--->onActivityCreated
BlankFragment2--->onStart
BlankFragment2--->onResume <<=================== 當前頁

鎖屏
lankFragment2--->onPause
AddShowHideFragmentActivity--->onPause
BlankFragment2--->onStop
AddShowHideFragmentActivity--->onStop
AddShowHideFragmentActivity--->onSaveInstanceState

解鎖屏幕
AddShowHideFragmentActivity--->onRestart
BlankFragment2--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當前頁

HOME回到桌面
BlankFragment2--->onPause
AddShowHideFragmentActivity--->onPause
BlankFragment2--->onStop
AddShowHideFragmentActivity--->onStop
AddShowHideFragmentActivity--->onSaveInstanceState

返回app頁面
AddShowHideFragmentActivity--->onRestart
BlankFragment2--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當前頁

跳轉新頁面
BlankFragment2--->onPause
AddShowHideFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
BlankFragment2--->onStop
AddShowHideFragmentActivity--->onStop
AddShowHideFragmentActivity--->onSaveInstanceState

返回ViewPager的頁面
MMKVActivity--->onPause
AddShowHideFragmentActivity--->onRestart
BlankFragment2--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當前頁

4) Fragment嵌套Fragment內的add show hide Fragment

外層的activity只是add一個fragment

/**
 * fragment內的viewpager內的fragment懶加載
 */
public class AddShowHideFragmentInFragmentActivity extends BindActivity implements AddFragmentInFragment.OnFragmentInteractionListener ,BlankFragment1.OnFragmentInteractionListener, BlankFragment2.OnFragmentInteractionListener, BlankFragment3.OnFragmentInteractionListener {

  @Override
  protected int setLayoutID() {
    return R.layout.activity_lazy_fragment;
  }

  @Override
  protected void initViews(Bundle savedInstanceState) {
    FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.fl_content,AddFragmentInFragment.newInstance("",""));
    transaction.commit();
  }

  @Override
  public void onFragmentInteraction(Uri uri) {

  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
  }
}

內部的fragment代碼如下

/**
 * add hide show顯示的fragment 嵌套在 外層fragment內
 */
public class AddFragmentInFragment extends BaseFragment {

  private static final String ARG_PARAM1 = "param1";
  private static final String ARG_PARAM2 = "param2";

  private String mParam1;
  private String mParam2;

  private OnFragmentInteractionListener mListener;

  private static final String KEY_FRAGMENT_1 = "1";
  private static final String KEY_FRAGMENT_2 = "2";
  private static final String KEY_FRAGMENT_3 = "3";

  @BindView(R.id.tab_title)
  CommonTabLayout commonTabLayout;
  @BindView(R.id.tv_next)
  TextView tv_next;
  BlankFragment1 blankFragment1;
  BlankFragment2 blankFragment2;
  BlankFragment3 blankFragment3;
  List<Fragment> fragmentList;

  public AddFragmentInFragment() {
  }

  public static AddFragmentInFragment newInstance(String param1, String param2) {
    AddFragmentInFragment fragment = new AddFragmentInFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
  }

  @Override
  public void onSaveInstanceState(@NonNull Bundle outState) {
    if(blankFragment1 != null&&blankFragment1.isAdded()) {
      mActivity.getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_1,blankFragment1);
    }
    if(blankFragment2 != null&&blankFragment2.isAdded()){
      mActivity.getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_2,blankFragment2);
    }
    if(blankFragment3 != null&&blankFragment3.isAdded()){
      mActivity.getSupportFragmentManager().putFragment(outState,KEY_FRAGMENT_3,blankFragment3);
    }
    super.onSaveInstanceState(outState);
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      mParam1 = getArguments().getString(ARG_PARAM1);
      mParam2 = getArguments().getString(ARG_PARAM2);
    }

  }

  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    tv_next.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent=new Intent(mContext, MMKVActivity.class);
        startActivity(intent);
      }
    });
    if(savedInstanceState != null){
      blankFragment1 = (BlankFragment1)mActivity.getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_1);
      blankFragment2 = (BlankFragment2)mActivity.getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_2);
      blankFragment3 = (BlankFragment3)mActivity.getSupportFragmentManager().getFragment(savedInstanceState,KEY_FRAGMENT_3);
    }
    fragmentList=new ArrayList<>();
    if (blankFragment1==null){
      fragmentList.add(blankFragment1=BlankFragment1.newInstance("11111",""));
    }else {
      fragmentList.add(blankFragment1);
    }
    if (blankFragment2==null){
      fragmentList.add(blankFragment2=BlankFragment2.newInstance("222222",""));
    }else {
      fragmentList.add(blankFragment2);
    }
    if (blankFragment3==null){
      fragmentList.add(blankFragment3=BlankFragment3.newInstance("3333333",""));
    }else {
      fragmentList.add(blankFragment3);
    }

    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    tabEntities.add(new TabLayoutEntity("商品1"));
    tabEntities.add(new TabLayoutEntity("評價2"));
    tabEntities.add(new TabLayoutEntity("詳情3"));
    commonTabLayout.setTabData(tabEntities);
    commonTabLayout.setCurrentTab(0);
    showFragment(fragmentList.get(0),false);
    commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override
      public void onTabSelect(int position) {
        showFragment(fragmentList.get(position),false);
      }

      @Override
      public void onTabReselect(int position) {
        showFragment(fragmentList.get(position),false);
      }
    });

  }

  private void showFragment(Fragment fragment,boolean replace){
    FragmentTransaction transaction = mActivity.getSupportFragmentManager().beginTransaction();
    if (replace){
      transaction.replace(R.id.fl_in_content,fragment);
    }else {
      if (!fragment.isAdded()){
        transaction.add(R.id.fl_in_content,fragment,fragment.getClass().getSimpleName());
      }
      hideAllFragment(transaction,fragment);
      transaction.show(fragment);
      transaction.setMaxLifecycle(fragment, Lifecycle.State.RESUMED);
    }
    transaction.commit();
  }
  private void hideAllFragment(FragmentTransaction transaction,Fragment withoutFragment){
    for (int i = 0; i < fragmentList.size(); i++) {
      if (!fragmentList.get(i).equals(withoutFragment)&&fragmentList.get(i).isAdded()){
        transaction.hide(fragmentList.get(i));
        transaction.setMaxLifecycle(fragmentList.get(i), Lifecycle.State.CREATED);
      }
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_main, container, false);
  }

  public void onButtonPressed(Uri uri) {
    if (mListener != null) {
      mListener.onFragmentInteraction(uri);
    }
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
      mListener = (OnFragmentInteractionListener) context;
    } else {
      throw new RuntimeException(context.toString()
          + " must implement OnFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  public interface OnFragmentInteractionListener {
    void onFragmentInteraction(Uri uri);
  }
}

實測日志可以發現,哪怕fragment是嵌套過的,Fragment的onResume生命周期也只會在當前頁顯示時調用:

首次進入 顯示第一頁
AddShowHideFragmentInFragmentActivity--->onCreate
AddFragmentInFragment--->onAttach
AddFragmentInFragment--->onCreate
AddFragmentInFragment--->onViewCreated
AddFragmentInFragment--->onActivityCreated
BlankFragment1--->onAttach
BlankFragment1--->onCreate
BlankFragment1--->onViewCreated
BlankFragment1--->onActivityCreated
AddFragmentInFragment--->onStart
BlankFragment1--->onStart
AddShowHideFragmentInFragmentActivity--->onStart
AddShowHideFragmentInFragmentActivity--->onResume
AddFragmentInFragment--->onResume
BlankFragment1--->onResume <<=================== 當前頁

點擊顯示第二頁
BlankFragment2--->onAttach
BlankFragment2--->onCreate
BlankFragment1--->onHiddenChanged=true
BlankFragment1--->onPause
BlankFragment1--->onStop
BlankFragment1--->onDestroyView
BlankFragment2--->onViewCreated
BlankFragment2--->onActivityCreated
BlankFragment2--->onStart
BlankFragment2--->onResume <<=================== 當前頁

鎖屏
AddFragmentInFragment--->onPause
BlankFragment2--->onPause
AddShowHideFragmentInFragmentActivity--->onPause
AddFragmentInFragment--->onStop
BlankFragment2--->onStop
AddShowHideFragmentInFragmentActivity--->onStop
AddShowHideFragmentInFragmentActivity--->onSaveInstanceState

解鎖屏幕
AddShowHideFragmentInFragmentActivity--->onRestart
AddFragmentInFragment--->onStart
BlankFragment2--->onStart
AddShowHideFragmentInFragmentActivity--->onStart
AddShowHideFragmentInFragmentActivity--->onResume
AddFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當前頁
HOME回到桌面
AddFragmentInFragment--->onPause
BlankFragment2--->onPause
AddShowHideFragmentInFragmentActivity--->onPause
AddFragmentInFragment--->onStop
BlankFragment2--->onStop
AddShowHideFragmentInFragmentActivity--->onStop
AddShowHideFragmentInFragmentActivity--->onSaveInstanceState

返回app頁面
AddShowHideFragmentInFragmentActivity--->onRestart
AddFragmentInFragment--->onStart
BlankFragment2--->onStart
AddShowHideFragmentInFragmentActivity--->onStart
AddShowHideFragmentInFragmentActivity--->onResume
AddFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當前頁

跳轉新頁面
AddFragmentInFragment--->onPause
BlankFragment2--->onPause
AddShowHideFragmentInFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
AddFragmentInFragment--->onStop
BlankFragment2--->onStop
AddShowHideFragmentInFragmentActivity--->onStop
AddShowHideFragmentInFragmentActivity--->onSaveInstanceState

返回當前頁
MMKVActivity--->onPause
AddShowHideFragmentInFragmentActivity--->onRestart
AddFragmentInFragment--->onStart
BlankFragment2--->onStart
AddShowHideFragmentInFragmentActivity--->onStart
AddShowHideFragmentInFragmentActivity--->onResume
AddFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當前頁

三、小結

上面列舉了四種不同的使用場景,以及各種常見的操作邏輯,除了保證頁面只有顯示為當前頁時才顯示onResume生命周期函數外,也通過saveState方法解決了fragment銷毀后,重疊顯示的UI異常。

看完這篇關于解決androidx下的fragment的lazy懶加載問題的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

嘉定区| 梧州市| 临漳县| 小金县| 平乡县| 固原市| 阿图什市| 长宁县| 高唐县| 肃宁县| 正安县| 繁昌县| 比如县| 宁波市| 莎车县| 龙岩市| 黑水县| 芒康县| 循化| 济阳县| 张掖市| 库伦旗| 连云港市| 万盛区| 改则县| 皋兰县| 上栗县| 茌平县| 开鲁县| 游戏| 宝鸡市| 托里县| 蒙山县| 峡江县| 阜平县| 景宁| 馆陶县| 绥芬河市| 土默特右旗| 金沙县| 龙门县|