Android如何实现仿微信Viewpager-Fragment惰性加载

发布时间:2021-06-28 09:47:45 作者:小新
来源:亿速云 阅读:87

这篇文章将为大家详细讲解有关Android如何实现仿微信Viewpager-Fragment惰性加载,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

效果如图:

Android如何实现仿微信Viewpager-Fragment惰性加载

什么是lazy-loading呢?顾名思义就是在必要的时候才加载,否则不进行View的绘制和数据的加载。原因是Viewpager一次只会显示一个页卡,那么刚开始的时候,只需加载第一张Fragment页卡,其他的不加载,当用户向右滑动切换再进行加载。因为其他Fragment对于用户来说是不可见的,如果一开始就把全部Fragment一起加载,可能造成启动时卡顿的问题,更重要的是可能白白耗费用户的流量,因为用户可能并不需要其他Fragment的信息。

今天Google了有关Fragment惰性加载的资料,并没有找到介绍得清楚详细的博文+demo。所以我找到了Github上的一个开源项目demo里有关惰性加载的代码,学习了这个知识点,并把它整理出来分享给大家。

你应该知道

你应该知道viewPager.setOffscreenPageLimit();方法。该方法设置ViewPager允许有多少张pages存在于屏幕外(不包括正在显示的page),默认值是1。在范围之外的pages 的View会被销毁,即onDestroyView()会被执行。

Viewpager里面FragmentPagerAdapter、FragmentStatePagerAdapter的区别:

1.FragmentPagerAdapter会将每一个生成的Fragment都放到内存中,即无论怎么滑动切换ViewPager,都不会有一个Fragment的onDestroy方法被调用。但Fragment不在viewPager.setOffscreenPageLimit(3);保护的范围内会调用FragmentManager的detach()方法,相应的Fragment的onDestroyView会执行,但Fragment实例仍在!所以该类适用于需要展示的Fragment比较少的情况。

2.FragmentStateAdapter 有点类似于LIstview的RecyclerBin机制,当Fragment不在viewPager.setOffscreenPageLimit(3);保护的范围内,Fragment的就会被销毁,onDestroy()、onDetach()方法会被执行。适用于要展示Fragment数量比较多,Fragment的子View和数据量复杂的情况。
熟知Fragment的生命周期。

Android如何实现仿微信Viewpager-Fragment惰性加载

Fragment的生命周期

3.刚被new出来的Fragment并没有开始它的生命周期,当它被添加到FragmentManager时生命周期才开始。

4.我们通常是在onCreateView()中对Fragment完成视图的构建。若是要实现延迟加载,可以在调用onCreateView时获得一个空container的引用。当等待用户切换到屏幕的时候,开始加载数据和视图。

那么如何得知我们的Fragment何时被切换到屏幕呢?核心方法就是getUserVisibleHint()和在Fragment中重写setUserVisibleHint(boolean isVisibleToUser){…}方法。

在官方文档是这样描述该方法的:

public void setUserVisibleHint (boolean isVisibleToUser)
Added in API level 15
Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.
An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.
Parameters
isVisibleToUser true if this fragment's UI is currently visible to the user (default), false if it is not.

该方法的作用是设置一个提示或者标志,该标志代表的是Fragment在当前是否处于对用户的可见状态。注意这里的可见并不能与Activity或Fragment的onStart或者onResume混淆。因为Fragment处于onResume状态并不代表它对用户是可见的!仍觉得很困惑?那我们一起来Log一下吧。

我们把生命周期回调方法加了Log语句。

  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    Log.d("TAG", "setUserVisibleHint() called with: " + "isVisibleToUser = [" + isVisibleToUser + "]");
  }

我们允许有4张页卡的缓存,因为微信是有4个tab的。这样ViewPager来回切换就不会有页卡被销毁了。

viewPager.setOffscreenPageLimit(3);

启动ViewPager后的Log:

D/TAG: setUserVisibleHint() called with: isVisibleToUser = [false]
D/TAG: setUserVisibleHint() called with: isVisibleToUser = [false]
D/TAG: setUserVisibleHint() called with: isVisibleToUser = [false]
D/TAG: setUserVisibleHint() called with: isVisibleToUser = [false]
D/TAG: setUserVisibleHint() called with: isVisibleToUser = [true]
D/TAG: onCreateView() : getUserVisibleHint():true
D/TAG: onStart() : getUserVisibleHint():true
D/TAG: onResume() : getUserVisibleHint():true
D/TAG: onCreateView() : getUserVisibleHint():false
D/TAG: onCreateView() : getUserVisibleHint():false
D/TAG: onCreateView() : getUserVisibleHint():false
D/TAG: onStart() : getUserVisibleHint():false
D/TAG: onResume() : getUserVisibleHint():false
D/TAG: onStart() : getUserVisibleHint():false
D/TAG: onResume() : getUserVisibleHint():false
D/TAG: onStart() : getUserVisibleHint():false
D/TAG: onResume() : getUserVisibleHint():false

从Log中,可得知,setUserVisibleHint()比onCreateView()先调用,并且只有一个方法的isVisbleToUser==true。由此我们可以断定,正在展示的fragment对应的isVisibleToUser才为true。我们现在有4个page,onCreateView()、onStart()、onResume()分别共调用了4次,由此可知,尽管Fragment没有被展示,ViewPager也会将它们构建起来,会回调onStart、onResume。那么ViewPager初始化时构建Fragment的个数与什么有关呢?这个主要跟使用的Adapter类型和setOffscreenPageLimit()有关。

接下来向右滑,切换到第二页,Log如下:

D/TAG: setUserVisibleHint() called with: isVisibleToUser = [false]
D/TAG: setUserVisibleHint() called with: isVisibleToUser = [true]

这次只会调用两次setUserVisibleHint(),将要刚刚显示的Fragment的isVisibleToUser 设置为false,并把将要显示的Fragment的isVisibleToUser 设置为true。

当我退出程序,Log如下:

D/TAG: onPause() : getUserVisibleHint():true
D/TAG: onPause() : getUserVisibleHint():false
D/TAG: onPause() : getUserVisibleHint():false
D/TAG: onPause() : getUserVisibleHint():false
D/TAG: onStop() called: getUserVisibleHint():true
D/TAG: onStop() called: getUserVisibleHint():false
D/TAG: onStop() called: getUserVisibleHint():false
D/TAG: onStop() called: getUserVisibleHint():false
D/TAG: onDestroyView() : getUserVisibleHint():true
D/TAG: onDestroy() :
D/TAG: onDetach() :
D/TAG: onDestroyView() : getUserVisibleHint():false
D/TAG: onDestroy() :
D/TAG: onDetach() :
D/TAG: onDestroyView() : getUserVisibleHint():false
D/TAG: onDestroy() :
D/TAG: onDetach() :
D/TAG: onDestroyView() : getUserVisibleHint():false
D/TAG: onDestroy() :
D/TAG: onDetach() :

从这“死亡日志”中,我们发现,getUserVisibleHint()贯穿着Fragment的凋亡生命线。
到此,对这个关键的方法,我们算是有了一个宏观的认识。

具体实现

那么具体应该怎么实现呢?我们可以在自定义一个抽象类LazyFragment,重写onCreateView()方法,只返回一个简单的,甚至是空的(不是null)的ViewGroup作为Container,比如return new FrameLayout();当然这个ViewGroup我们需要保存为成员变量。接下来重写setUserVisibleHint(boolean isVisibleToUser)方法,如果该Fragment处于用户可见状态,就会调用该方法,并传过来的isVisibleToUser==true。所以根据这个hint做一个判断,若等于true,立即加载原本要正常显示的视图和数据。当然这个方法可以作为一个抽象方法交给子类去实现。具体的实现就是这样!Talk is simple,show you the code!

LazyFragment:

省去了一些,回调方法,只给出了核心的几个方法,完整的可以看文章末尾的项目源码。注释已经写得相对完善,如果有不明白的地方欢迎评论留言。

public class LazyFragment extends BaseFragment {
 private boolean isInit = false;//真正要显示的View是否已经被初始化(正常加载)
 private Bundle savedInstanceState;
 public static final String INTENT_BOOLEAN_LAZYLOAD = "intent_boolean_lazyLoad";
 private boolean isLazyLoad = true;
 private FrameLayout layout;
 private boolean isStart = false;//是否处于可见状态,in the screen

 @Deprecated
 protected final void onCreateView(Bundle savedInstanceState) {
  Log.d("TAG", "onCreateView() : " + "getUserVisibleHint():" + getUserVisibleHint());
  super.onCreateView(savedInstanceState);
  Bundle bundle = getArguments();
  if (bundle != null) {
   isLazyLoad = bundle.getBoolean(INTENT_BOOLEAN_LAZYLOAD, isLazyLoad);
  }
  //判断是否懒加载
  if (isLazyLoad) {
   //处于完全可见、没被初始化的状态,调用onCreateViewLazy显示内容
   if (getUserVisibleHint() && !isInit) {
    this.savedInstanceState = savedInstanceState;
    onCreateViewLazy(savedInstanceState);
    isInit = true;
   } else {
    //进行懒加载
    layout = new FrameLayout(getApplicationContext());
    layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.fragment_lazy_loading, null);
    layout.addView(view);
    super.setContentView(layout);
   }
  } else {
   //不需要懒加载,开门江山,调用onCreateViewLazy正常加载显示内容即可
   onCreateViewLazy(savedInstanceState);
   isInit = true;
  }
 }

 @Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
  super.setUserVisibleHint(isVisibleToUser);
  Log.d("TAG", "setUserVisibleHint() called with: " + "isVisibleToUser = [" + isVisibleToUser + "]");
  //一旦isVisibleToUser==true即可对真正需要的显示内容进行加载

  //可见,但还没被初始化
  if (isVisibleToUser && !isInit && getContentView() != null) {
   onCreateViewLazy(savedInstanceState);
   isInit = true;
   onResumeLazy();
  }
  //已经被初始化(正常加载)过了
  if (isInit && getContentView() != null) {
   if (isVisibleToUser) {
    isStart = true;
    onFragmentStartLazy();
   } else {
    isStart = false;
    onFragmentStopLazy();
   }
  }
 }

 @Override
 public void setContentView(int layoutResID) {
  //判断若isLazyLoad==true,移除所有lazy view,加载真正要显示的view
  if (isLazyLoad && getContentView() != null && getContentView().getParent() != null) {
   layout.removeAllViews();
   View view = inflater.inflate(layoutResID, layout, false);
   layout.addView(view);
  }
  //否则,开门见山,直接加载
  else {
   super.setContentView(layoutResID);
  }
 }

 @Override
 public void setContentView(View view) {
  //判断若isLazyLoad==true,移除所有lazy view,加载真正要显示的view
  if (isLazyLoad && getContentView() != null && getContentView().getParent() != null) {
   layout.removeAllViews();
   layout.addView(view);
  }
  //否则,开门见山,直接加载
  else {
   super.setContentView(view);
  }
 }
}

具体的实现类:

public class MoreFragment extends LazyFragment {
 private TextView tvLoading;
 private ImageView ivContent;
 private int tabIndex;
 public static final String INTENT_INT_INDEX="index";

 public static MoreFragment newInstance(int tabIndex) {

  Bundle args = new Bundle();
  args.putInt(INTENT_INT_INDEX, tabIndex);
  MoreFragment fragment = new MoreFragment();
  fragment.setArguments(args);
  return fragment;
 }
 @Override
 protected void onCreateViewLazy(Bundle savedInstanceState) {
  super.onCreateViewLazy(savedInstanceState);
  setContentView(R.layout.fragment_tabmain_item);
  tabIndex = getArguments().getInt(INTENT_INT_INDEX);
  ivContent = (ImageView) findViewById(R.id.iv_content);
  tvLoading = (TextView) findViewById(R.id.tv_loading);
  getData();
 }

 private void getData() {
  new Thread(new Runnable() {
   @Override
   public void run() {
    //异步处理加载数据
    //...
    //完成后,通知主线程更新UI
    handler.sendEmptyMessageDelayed(1, 2000);
   }
  }).start();
 }

 @Override
 public void onDestroyViewLazy() {
  super.onDestroyViewLazy();
  handler.removeMessages(1);
 }

 private Handler handler = new Handler() {
  public void handleMessage(android.os.Message msg) {
   tvLoading.setVisibility(View.GONE);
   int id=0;
   switch (tabIndex){
    case 1:
     id=R.drawable.a;
     break;
    case 2:
     id=R.drawable.b;
     break;
    case 3:
     id=R.drawable.c;
     break;
    case 4:
     id=R.drawable.d;
     break;
   }
   ivContent.setImageResource(id);
   ivContent.setVisibility(View.VISIBLE);
  }
 };
}

为了简化布局,demo中只用了微信上的几张截图,希望大家能专注重点。具体效果如图:

Android如何实现仿微信Viewpager-Fragment惰性加载

关于“Android如何实现仿微信Viewpager-Fragment惰性加载”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. Android仿微信下拉列表实现
  2. Android仿微信录音功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android

上一篇:Android如何实现仿微信@好友功能

下一篇:Android如何实现仿银行客户签名功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》