欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

androidx下的fragment的lazy懒加载问题详解

程序员文章站 2023-11-07 16:53:58
网上关于androidx的fragment懒加载文章已经有很多,各有侧重。几乎都点到了sexmaxlifecycle和修改fragmentpageradapter。很少看到经过实践的文章,谨以此文,更...

网上关于androidx的fragment懒加载文章已经有很多,各有侧重。几乎都点到了sexmaxlifecycle和修改fragmentpageradapter。很少看到经过实践的文章,谨以此文,更加详尽的把实践后的结果记录下来,赠予有缘人。

一、前置准备工作

几个关于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

<?xml version="1.0" encoding="utf-8"?>
<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

<?xml version="1.0" encoding="utf-8"?>
<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

<?xml version="1.0" encoding="utf-8"?>
<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懒加载问题详解的文章就介绍到这了,更多相关androidx fragment lazy懒加载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!