真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

解決androidx下的fragment的lazy懶加載問(wèn)題

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

我們提供的服務(wù)有:網(wǎng)站設(shè)計(jì)制作、成都做網(wǎng)站、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、石龍ssl等。為成百上千企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的石龍網(wǎng)站制作公司

一、前置準(zhǔn)備工作

幾個(gè)關(guān)于androidx的fragment懶加載方案,都離不開(kāi)如下幾個(gè)包:

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

我在實(shí)際測(cè)試代碼中使用了如下版本,可供參考:

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

還準(zhǔn)備了4個(gè)Activity與5個(gè)Fragment:

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

相應(yīng)的幾個(gè)簡(jiǎn)單布局文件:

文件:fragment_main.xml

加載ViewPager控件和AddShow使用的FrameLayout,以及測(cè)試跳轉(zhuǎn)后返回的TextView按鈕。

fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>


  

  

  

  

文件:activity_lazy_fragment.xml

這里是測(cè)試fragment嵌套情況下的布局,fl_content用來(lái)加載fragment

activity_lazy_fragment.xml

<?xml version="1.0" encoding="utf-8"?>


  

文件:fragment_blank.xml

這一個(gè)空f(shuō)ragment就沒(méi)什么講究了

fragment_blank.xml

<?xml version="1.0" encoding="utf-8"?>


  

二、具體代碼分析

1) ViewPager+Fragment

最常見(jiàn)的使用方式,由ViewPager滑動(dòng)顯示多個(gè)Fragment,直接上代碼:

activity頁(yè)面代碼

其中就是個(gè)簡(jiǎn)單的viewpager設(shè)置adapter然后加載fragment集合顯示

/**
 * viewpager內(nèi)的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 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頁(yè)面代碼

新版FragmentPagerAdapter多了2個(gè)常量

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

用在了構(gòu)造方法中

/**
   * 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;
  }

我們只需要在構(gòu)造adapter時(shí),使用BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT這個(gè)常量就行

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

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

  public BaseFragmentXPagerAdapter(@NonNull FragmentManager fm,List fragmentList,List fragmentTitleList) {
    this(fm,fragmentList,fragmentTitleList,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
  }
  public BaseFragmentXPagerAdapter(@NonNull FragmentManager fm,List fragmentList,List 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

最終打印生命周期日志,確認(rèn)結(jié)果,viewPager+fragment搭配pagerAdapter的behavior在各種情況下的日志,可以看出新版viewPager+pagerAdapter實(shí)測(cè)下來(lái),Fragment的onResume生命周期只會(huì)在當(dāng)前頁(yè)顯示時(shí)調(diào)用

首次進(jìn)入 顯示第一頁(yè)
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 <<=================== 當(dāng)前頁(yè)

滑動(dòng)到第二頁(yè)
BlankFragment3--->onAttach
BlankFragment3--->onCreate
BlankFragment3--->onViewCreated
BlankFragment3--->onActivityCreated
BlankFragment3--->onStart
BlankFragment1--->onPause
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

鎖屏
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 <<=================== 當(dāng)前頁(yè)

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

返回app頁(yè)面
ViewPagerFragmentActivity--->onRestart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentActivity--->onStart
ViewPagerFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

跳轉(zhuǎn)新頁(yè)面
BlankFragment2--->onPause
ViewPagerFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
BlankFragment1--->onStop
BlankFragment2--->onStop
BlankFragment3--->onStop
ViewPagerFragmentActivity--->onStop
ViewPagerFragmentActivity--->onSaveInstanceState

返回ViewPager的頁(yè)面
MMKVActivity--->onPause
ViewPagerFragmentActivity--->onRestart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentActivity--->onStart
ViewPagerFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)
MMKVActivity--->onStop
MMKVActivity--->onDestroy

2) Fragment嵌套Fragment內(nèi)的ViewPager+Fragment

外層的activity只是add一個(gè)fragment

/**
 * fragment內(nèi)的viewpager內(nèi)的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在一個(gè)fragment內(nèi)
 */
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 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);
  }
}

實(shí)測(cè)日志可以發(fā)現(xiàn),哪怕fragment是嵌套過(guò)的,F(xiàn)ragment的onResume生命周期也只會(huì)在當(dāng)前頁(yè)顯示時(shí)調(diào)用:

首次進(jìn)入顯示第一頁(yè)
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 <<=================== 當(dāng)前頁(yè)

滑動(dòng)到第二頁(yè)
BlankFragment3--->onAttach
BlankFragment3--->onCreate
BlankFragment3--->onViewCreated
BlankFragment3--->onActivityCreated
BlankFragment3--->onStart
BlankFragment1--->onPause
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

鎖屏
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 <<=================== 當(dāng)前頁(yè)

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

返回app頁(yè)面
ViewPagerFragmentInFragmentActivity--->onRestart
ViewPagerFragmentInFragment--->onStart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentInFragmentActivity--->onStart
ViewPagerFragmentInFragmentActivity--->onResume
ViewPagerFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

跳轉(zhuǎn)新頁(yè)面
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的頁(yè)面
MMKVActivity--->onPause
ViewPagerFragmentInFragmentActivity--->onRestart
ViewPagerFragmentInFragment--->onStart
BlankFragment1--->onStart
BlankFragment2--->onStart
BlankFragment3--->onStart
ViewPagerFragmentInFragmentActivity--->onStart
ViewPagerFragmentInFragmentActivity--->onResume
ViewPagerFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

3) 通過(guò)add show hide操作多個(gè)fragment

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

通過(guò)hide隱藏的頁(yè)面,設(shè)置transaction.setMaxLifecycle(fragmentList.get(i), Lifecycle.State.CREATED),使隱藏了的fragment生命周期只能走到創(chuàng)建階段,無(wú)法走到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 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 tabEntities = new ArrayList<>();
    tabEntities.add(new TabLayoutEntity("商品1"));
    tabEntities.add(new TabLayoutEntity("評(píng)價(jià)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);
  }
}

首次進(jìn)入 顯示第一頁(yè)
AddShowHideFragmentActivity--->onCreate
BlankFragment1--->onAttach
BlankFragment1--->onCreate
BlankFragment1--->onViewCreated
BlankFragment1--->onActivityCreated
BlankFragment1--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment1--->onResume <<=================== 當(dāng)前頁(yè)

點(diǎn)擊顯示第二頁(yè)
BlankFragment2--->onAttach
BlankFragment2--->onCreate
BlankFragment1--->onHiddenChanged=true
BlankFragment1--->onPause
BlankFragment1--->onStop
BlankFragment1--->onDestroyView
BlankFragment2--->onViewCreated
BlankFragment2--->onActivityCreated
BlankFragment2--->onStart
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

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

解鎖屏幕
AddShowHideFragmentActivity--->onRestart
BlankFragment2--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

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

返回app頁(yè)面
AddShowHideFragmentActivity--->onRestart
BlankFragment2--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

跳轉(zhuǎn)新頁(yè)面
BlankFragment2--->onPause
AddShowHideFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
BlankFragment2--->onStop
AddShowHideFragmentActivity--->onStop
AddShowHideFragmentActivity--->onSaveInstanceState

返回ViewPager的頁(yè)面
MMKVActivity--->onPause
AddShowHideFragmentActivity--->onRestart
BlankFragment2--->onStart
AddShowHideFragmentActivity--->onStart
AddShowHideFragmentActivity--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

4) Fragment嵌套Fragment內(nèi)的add show hide Fragment

外層的activity只是add一個(gè)fragment

/**
 * fragment內(nèi)的viewpager內(nèi)的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);
  }
}

內(nèi)部的fragment代碼如下

/**
 * add hide show顯示的fragment 嵌套在 外層fragment內(nèi)
 */
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 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 tabEntities = new ArrayList<>();
    tabEntities.add(new TabLayoutEntity("商品1"));
    tabEntities.add(new TabLayoutEntity("評(píng)價(jià)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);
  }
}

實(shí)測(cè)日志可以發(fā)現(xiàn),哪怕fragment是嵌套過(guò)的,F(xiàn)ragment的onResume生命周期也只會(huì)在當(dāng)前頁(yè)顯示時(shí)調(diào)用:

首次進(jìn)入 顯示第一頁(yè)
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 <<=================== 當(dāng)前頁(yè)

點(diǎn)擊顯示第二頁(yè)
BlankFragment2--->onAttach
BlankFragment2--->onCreate
BlankFragment1--->onHiddenChanged=true
BlankFragment1--->onPause
BlankFragment1--->onStop
BlankFragment1--->onDestroyView
BlankFragment2--->onViewCreated
BlankFragment2--->onActivityCreated
BlankFragment2--->onStart
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

鎖屏
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 <<=================== 當(dāng)前頁(yè)
HOME回到桌面
AddFragmentInFragment--->onPause
BlankFragment2--->onPause
AddShowHideFragmentInFragmentActivity--->onPause
AddFragmentInFragment--->onStop
BlankFragment2--->onStop
AddShowHideFragmentInFragmentActivity--->onStop
AddShowHideFragmentInFragmentActivity--->onSaveInstanceState

返回app頁(yè)面
AddShowHideFragmentInFragmentActivity--->onRestart
AddFragmentInFragment--->onStart
BlankFragment2--->onStart
AddShowHideFragmentInFragmentActivity--->onStart
AddShowHideFragmentInFragmentActivity--->onResume
AddFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

跳轉(zhuǎn)新頁(yè)面
AddFragmentInFragment--->onPause
BlankFragment2--->onPause
AddShowHideFragmentInFragmentActivity--->onPause
MMKVActivity--->onCreate
MMKVActivity--->onStart
MMKVActivity--->onResume
AddFragmentInFragment--->onStop
BlankFragment2--->onStop
AddShowHideFragmentInFragmentActivity--->onStop
AddShowHideFragmentInFragmentActivity--->onSaveInstanceState

返回當(dāng)前頁(yè)
MMKVActivity--->onPause
AddShowHideFragmentInFragmentActivity--->onRestart
AddFragmentInFragment--->onStart
BlankFragment2--->onStart
AddShowHideFragmentInFragmentActivity--->onStart
AddShowHideFragmentInFragmentActivity--->onResume
AddFragmentInFragment--->onResume
BlankFragment2--->onResume <<=================== 當(dāng)前頁(yè)

三、小結(jié)

上面列舉了四種不同的使用場(chǎng)景,以及各種常見(jiàn)的操作邏輯,除了保證頁(yè)面只有顯示為當(dāng)前頁(yè)時(shí)才顯示onResume生命周期函數(shù)外,也通過(guò)saveState方法解決了fragment銷毀后,重疊顯示的UI異常。

看完這篇關(guān)于解決androidx下的fragment的lazy懶加載問(wèn)題的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話,可以把它分享出去給更多人看到。


分享標(biāo)題:解決androidx下的fragment的lazy懶加載問(wèn)題
網(wǎng)站地址:http://weahome.cn/article/gjddcc.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部