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

网上关于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懒加载内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解Android 在 ViewPager 中使用 Fragment 的懒加载

    我们先看一下效果: 首先,我们要知道什么是懒加载: 懒加载,就是先初始化控件,在用户可见的时候再加载数据. 为什么要懒加载? 懒加载多被使用在新闻资讯类客户端中,试想那么多的分类如果一下子都加载出来,真的是极大地消耗了系统资源.可能有人会说 ViewPager 有 viewPager.setOffscreenPageLimit() 的方法,我们传个 0 进去不就好了吗?看过源码的应该知道,即便你传了 0 进去,系统也会默认为 1 的,也就是 ViewPager 依然会加载当前页面的前后各一个 F

  • Android仿今日头条多个fragment懒加载的实现

    前言 最近有时间,所以我又双叒叕推新一篇文章了,fragment懒加载实现虽然是个小模块,但做过的人都有体会,通常并不会轻易就成功了的,让你辗转反侧,彻夜难眠,绵绵无绝期.我就按照今日头条的样式做了一个懒加载功能.文章到一半会解释大家可能遇到的不加载数据了的坑,先不剧透. Fragment的生命周期回顾 github代码直通车 (本地下载) 这里是今日头条效果: 自制效果,有图有真相: 实现思路: 使用Fragment类自带方法setUserVisibleHint()判断当前fragment是否

  • Android界面数据懒加载实现代码

    大家在使用手机新闻客户端的时候就会有一个发现,大多数的新闻客户端都会把新闻分类,诸如头条.娱乐.体育.科技等等,如何实现这种界面的呢?这个实现起来其实很简单,就是在一个Fragment中实现多个ViewPage的切换,再在ViewPage的上面放一个TabLayout,关联起来就可以实现联动效果.如果大家感觉不太明了的话,以后我可以专门写一篇关于Fragment中放入多个ViewPage的博客,今天,我主要介绍的是怎样实现界面即Fragment的懒加载.那么,大家就会奇怪了既然是加载界面直接加载

  • Android 多层嵌套后的 Fragment 懒加载实现示例

    多层嵌套后的 Fragment 懒加载 印象中从 Feed 流应用流行开始,Fragment 懒加载变成了一个大家都需要关注的开发知识,关于 Fragment 的懒加载,网上有很多例子,GitHub 上也有很多例子,就连我自己在一年前也写过相关的文章.但是之前的应用可能最多的是一层 Activity + ViewPager 的 UI 层次,但是随着页面越来越复杂,越来越多的应用首页一个页面外层是一个 ViewPager 内部可能还嵌套着一层 ViewPager,这是之前的懒加载就可能不那么好用了

  • Android之Viewpager+Fragment实现懒加载示例

    我们在做应用开发的时候,一个Activity里面可能会以viewpager(或其他容器)与多个Fragment来组合使用.而ViewPager默认会缓存三页数据,即:Viewpager每加载一个Fragment,都会预先加载此Fragment左侧或右侧的Fragment.而如果每个fragment都需要去加载数据,或从本地加载,或从网络加载,那么在这个activity刚创建的时候就变成需要初始化大量资源,浪费用户流量不止,还造成卡顿,这样的结果,我们当然不会满意.那么,能不能做到当切换到这个fr

  • Android在多种设计下实现懒加载机制的方法

    前言 前段时间在自己的练习项目中想用到懒加载机制,查看了大多数资料只介绍了在 View Pager + Fragment 组合的情况下实现的懒加载,但是现在大多数App更多的是 Fragmentmanager 去管理主页面多个 Fragment 的显示与隐藏,然后主界面的某个或多个 Fragment 里又嵌套了多个 Fragment + ViewPager (详细见下图 ),对于这种情况,适用于第一种的方式是不能直接解决第二种的情况的,所以写下这篇文章,记录一下踩的几个坑,希望对同像我一样的初学

  • Android开发技巧之Fragment的懒加载

    前言 所谓懒加载,就是当fragment完全可见的时候我们再去加载数据,我们在做应用开发的时候,一个Activity里面可能会以viewpager(或其他容器)与多个Fragment来组合使用,而如果每个fragment都需要去加载数据,或从本地加载,或从网络加载,那么在这个activity刚创建的时候就变成需要初始化大量资源.这样的结果,我们当然不会满意.那么,能不能做到当切换到这个fragment的时候,它才去初始化呢? 答案就在Fragment里的setUserVisibleHint这个方

  • android实现ViewPager懒加载的三种方法

    在项目中ViewPager和Fragment接口框架已经是处处可见,但是在使用中,我们肯定不希望用户在当前页面时就在前后页面的数据,加入数据量很大,而用户又不愿意左右滑动浏览,那么这时候ViewPager中本来充满善意的预加载就有点令人不爽了.我们能做的就是屏蔽掉ViewPager的预加载机制.虽然ViewPager中提供的有setOffscreenPageLimit()来控制其预加载的数目,但是当设置为0后我们发现其根本没效果,这个的最小值就是1,也就是你只能最少前后各预加载一页.那么,这时候

  • Android优化方案之Fragment的懒加载实现代码

    一.背景 在Android应用中,ViewPager是我们不可避免使用的一个控件,因为它可以使我们在占用较少空间的同时,增强内容的丰富性,同时以其内部流淌着Google的血液,所以它几乎成了每一个App的标配控件.但是,假如ViewPager的每一个Fragment都需要通过网络拉取数据加载,而ViewPager是默认加载前两项的,所以在很容易造成网络丢包或者网络堵塞等问题,所以Fragment使用懒加载是非常有必要的. 举个栗子: 如上图所示,我们有两个大的Tab:人物和风景.而人物Tab下有

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

    网上关于androidx的fragment懒加载文章已经有很多,各有侧重.几乎都点到了sexMaxLifecycle和修改FragmentPagerAdapter.很少看到经过实践的文章,谨以此文,更加详尽的把实践后的结果记录下来,赠予有缘人. 一.前置准备工作 几个关于androidx的fragment懒加载方案,都离不开如下几个包: androidx.fragment:fragment:1.1.0-alpha07 以上,支持setMaxLifecycle方法即可 androidx.viewp

  • React 悬浮框内容懒加载实例详解

    目录 界面隐藏 懒加载 React实现 原始代码 放入新的DIV 状态设置 样式设置 事件设置 事件优化 延迟显示悬浮框 悬浮框内容懒加载 完整代码 界面隐藏 一个容器放置视频,默认情况下 display: none; z-index: 0; transform: transform3d(10000px, true_y, true_z); y轴和z轴左边都是真实的(腾讯视频使用绝对定位,因此是计算得到的),只是将其移到右边很远的距离. 懒加载 React监听鼠标移入(获取坐标) 添加事件监听 o

  • vue前端性能优化之预加载和懒加载示例详解

    目录 预加载 图片预加载 JS预加载 js的加载方式 preload prefetch Preload & Prefetch 的区别 不同资源加载的优先级规则 懒加载 图片懒加载 路由懒加载 组件懒加载 最后 预加载 预加载简单来说就是将所有所需的资源提前请求加载到本地,这样后面在需要用到时就直接从缓存取资源:我们使用该技术预先告知浏览器,等下某些资源可能要被使用,先把资源下载下来,不要等使用的时候再下载,可以看出这样的加载技术会增加服务器的压力,但是用户的体验会比较好,因为可以较快的看到后面的

  • Vue lazyload图片懒加载实例详解

    文档:https://github.com/hilongjw/vue-lazyload 1.安装 cnpm i vue-lazyload -S 或 npm i vue-lazyload -S 2.实例 导入配置等操作 src/main.js import Vue from 'vue' import App from './App' import router from './router' //[1]导入懒加载 import VueLazyload from 'vue-lazyload' Vue

  • ionic2懒加载配置详解

    文章标题为part 1,并解释目前可以如此配置,但后续使用上可能还有变动. 以ion-cli默认home组件为例.添加home.module.ts文件 import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { HomePage } from './home'; @NgModule({ declarations: [HomePage], imports: [

  • hibernate 中 fetch=FetchType.LAZY 懒加载失败处理方法

    对这种懒加载问题,最后的做法是利用Spring提供的一个针对Hibernate的一个支持类,其主要意思是在发起一个页面请求时打开Hibernate的Session,一直保持这个Session,使得Hibernate的Session的生命周期变长,直到这个请求结束,具体是通过一个Filter来实现的. 那么,如果现在我们想用Hibernate懒加载特性,又想用延长session的生命周期,知道将数据提到页面显示(经过action层),那么我们就得在web.xml文件中增加以下配置: <!-- 配置

  • SpringIOC BeanDefinition的加载流程详解

    目录 一.前言 二. BeanDefinition 的体系 2.1 体系概览 2.2 BeanDefinition 的作用 三. BeanDefinition 的载入 3.1 载入的入口 3.2 保存的逻辑 3.3 使用的方式 总结 一.前言 这一篇来看看 SpringIOC 里面的一个细节点 , 来简单看看 BeanDefinition 这个对象 , 以及有没有办法对其进行定制. CASE 备份 :  gitee.com/antblack/ca… 二. BeanDefinition 的体系 2

  • classloader类加载器_基于java类的加载方式详解

    基础概念 Classloader 类加载器,用来加载 Java 类到 Java 虚拟机中.与普通程序不同的是.Java程序(class文件)并不是本地的可执行程序.当运行Java程序时,首先运行JVM(Java虚拟机),然后再把Java class加载到JVM里头运行,负责加载Java class的这部分就叫做Class Loader. JVM本身包含了一个ClassLoader称为Bootstrap ClassLoader,和JVM一样,BootstrapClassLoader是用本地代码实现

  • Android LayoutInflater加载布局详解及实例代码

    Android  LayoutInflater加载布局详解 对于有一定Android开发经验的同学来说,一定使用过LayoutInflater.inflater()来加载布局文件,但并不一定去深究过它的原理,比如 1.LayoutInflater为什么可以加载layout文件? 2.加载layout文件之后,又是怎么变成供我们使用的View的? 3.我们定义View的时候,如果需要在布局中使用,则必须实现带AttributeSet参数的构造方法,这又是为什么呢? 既然在这篇文章提出来,那说明这三

  • 基于js文件加载优化(详解)

    在js引擎部分,我们可以了解到,当渲染引擎解析到script标签时,会将控制权给JS引擎,如果script加载的是外部资源,则需要等待下载完后才能执行. 所以,在这里,我们可以对其进行很多优化工作. 放置在BODY底部 为了让渲染引擎能够及早的将DOM树给渲染出来,我们需要将script放在body的底部,让页面尽早脱离白屏的现象,即会提早触发DOMContentLoaded事件. 但是由于在IOS Safari, Android browser以及IOS webview里面即使你把js脚本放到

随机推荐