当前位置:网站首页>Fragment lazy load
Fragment lazy load
2022-07-26 10:51:00 【leilifengxingmw】
First, talk about something else : I bought my train ticket home today ,12306 Still didn't disappoint me , Decisively did not grab . I bought a plane ticket first , Then wait for tomorrow's train ticket , If you get it, you'll refund the plane ticket , Or you'll have to take a plane .
Record today Fragment Lazy loading
About Fragment Lazy loading of has the following two points to declare first :
1.Fragment Of setUserVisibleHint Method , Only Fragment stay ViewPager Will be called
// If isVisibleToUser by true, Indicates that the current interface is visible to the user
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}2.Fragment Of setUserVisibleHint Execution in onCreateView Before
Lazy loading :Fragment stay ViewPager When used in , When Fragment Load data only when it is visible to the user , This can reduce Activity Resources required for startup , Think about it , Once started Activity, There are more than one Fragment Load data together , It definitely needs a lot of resources .
Implementation steps
1. Definition BaseLazyFrament
public abstract class BaseLazyFragment extends Fragment {
protected String TAG = getClass().getSimpleName();
// Mark whether the layout has been initialized
protected boolean isViewCreated;
// Mark whether data has been loaded
protected boolean isLoadDataCompleted;
/** * Statement rootView, When Fragment call onCreateView Created on rootView, * When Fragment Switch to invisible and call onDestroyView When destroying views , * This rootView It's not going to be destroyed . When Fragment Switch back and call onCreateView Recreate the view * Of When , Go straight back to rootView. */
protected View rootView;
// This is used to display data in subclasses
protected RecyclerView rv;
public BaseLazyFragment() {
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e(TAG, "isVisibleToUser=" + isVisibleToUser);
// If at present Fragment so ,onCreateView Has been called , And no data has been loaded , Then load data
if (isVisibleToUser && isViewCreated && !isLoadDataCompleted) {
lazyLoadData();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(getLayout(), container, false);
ButterKnife.bind(this, rootView);
init(rootView);
//isViewCreated Set as true
isViewCreated = true;
}
return rootView;
}
/** * * Here we need to call once lazyLoadData , because ViewPage When showing the first page setUserVisibleHint * Precede onCreateView call , Now isViewCreated by false, No data will be loaded . * onActivityCreated stay onCreateView Then call , At this time, the view has been initialized * BI isViewCreated by true, So we load data here , Make sure the first page Fragment Normal display */
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getUserVisibleHint()) {
lazyLoadData();
}
}
// Get the layout file
protected abstract int getLayout();
// Initialize some view And related data
protected abstract void init(View view);
// Load data
protected void lazyLoadData() {
isLoadDataCompleted = true;
}
}
The code uses ButterKnife Conduct view binding , There's a point to make : Statement Member variables rootView, For preservation Fragment The view of , If in onCreateView Declare local variables rootView( As shown below ), So in Fragment call onDestroyView in the future , The user switches back onCreateView Call again , It can lead to some problems .
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.f1, container,false);
return rootView;
}for instance : In the beginning ,Fragment For the first time ,Fragment There is one of them. RecylerView, We set a adapter. Then we switch Fragment, Leading to the current Fragment invisible , And the view is destroyed . Then when we switch back ,Fragment The view will be recreated ( call onCreateView), Then we call adapter.notifyDataSetChanged(); Find it completely useless . Because after we recreate the view , Will recreate RecylerView example . This RecylerView It's not what we set adapter Of RecylerView 了 , So call adapter.notifyDataSetChanged() It doesn't work at all . About calling adapter.notifyDataSetChanged() For a more detailed discussion of what doesn't work, see here RecyclerView encounter notifyDataSetChanged Solution when invalid
2. It's over BaseLazyFrament, Then we define Fragment It is basically OK to realize it , In the following code getData Method in lazyLoadData Call in , Simulate loading data .
public class FirstLazyFragment extends BaseLazyFragment {
public static final String ID = "ID";
protected String TAG = getClass().getSimpleName();
@BindView(R.id.ptr_rv)
PullToRefreshRecyclerView pullToRefreshRecyclerView;
@BindView(R.id.tv_title)
TextView tvTitle;
private int id = -1;
private List<NotifyBean> data;
private NotifyAdapter adapter;
public FirstLazyFragment() {
// Required empty public constructor
}
public static FirstLazyFragment newInstance(int id) {
FirstLazyFragment fragment = new FirstLazyFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
@Override
protected int getLayout() {
return R.layout.fragment_lazy;
}
@Override
protected void init(View view) {
Log.e(TAG, "onCreateView init id=" + id);
tvTitle.setText("fragment id is " + id);
data = new ArrayList<>();
rv = pullToRefreshRecyclerView.getRefreshableView();
rv.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new NotifyAdapter(data);
rv.setAdapter(adapter);
pullToRefreshRecyclerView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
@Override
public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
getData();
}
});
}
@Override
protected void lazyLoadData() {
super.lazyLoadData();
Log.e(TAG, "lazyLoadData id=" + id);
getData();
}
private void getData() {
pullToRefreshRecyclerView.postDelayed(new Runnable() {
@Override
public void run() {
pullToRefreshRecyclerView.onRefreshComplete();
if (page <= 3) {
List<NotifyBean> tempList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
NotifyBean notifyBean = new NotifyBean(System.currentTimeMillis() / 1000, "page" + page + "i=" + i);
tempList.add(notifyBean);
}
data.addAll(tempList);
page++;
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getContext(), getString(R.string.load_all), Toast.LENGTH_SHORT).show();
pullToRefreshRecyclerView.setMode(PullToRefreshBase.Mode.DISABLED);
}
}
}, 500);
}
}3. Don't forget , Lazy loading is Fragment stay ViewPager Used in . Definition ViewPager Adapter for
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
4. stay Activity Use in
public class LazyLoadActivity extends AppCompatActivity {
@BindView(R.id.view_page)
ViewPager viewPage;
private List<Fragment> fragments;
public static void launch(Context context) {
Intent intent = new Intent(context, LazyLoadActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lazy_load);
ButterKnife.bind(this);
fragments = new ArrayList<>();
fragments.add(FirstLazyFragment.newInstance((1)));
fragments.add(SecondLazyFragment.newInstance((2)));
fragments.add(ThirdLazyFragment.newInstance((3)));
fragments.add(ForthLazyFragment.newInstance((4)));
viewPage.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), fragments));
}
}
For the complete code, please move to :https://github.com/humanheima/FragmentUseDemo, The following sentence is very important
demo Medium lazyload Under the folder is all the code for lazy loading
Reference link
1.https://www.jianshu.com/p/8a0f6b627e37
2.http://www.10tiao.com/html/169/201608/2650820834/1.html
3.http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1021/1813.html
边栏推荐
- C语言命名空间的定义与使用
- 菜鸟看源码之LinkedBlockingQueue
- Definition and use of C language namespace
- RT thread learning notes (VI) -- start the elmfat file system based on SPI flash (Part 1)
- 微信公众号消息通知 “errcode“:40164,“errmsg“:“invalid ip
- Bigdecimal的加减乘除、比较大小、向上向下取整 和 Bigdecimal的集合累加、判断BigDecimal是否有小数
- 使用Selenium抓取zabbix性能监控图
- 二叉树的遍历 递归+迭代
- MultipartFil转为File
- 面试过程中,面试官是如何考察Rust工程师的水平?
猜你喜欢

20210807 1 c language program structure

@NotBlank、@NotNull 、@NotEmpty 区别和使用

在神州IV开发板上成功移植STemWin V5.22

如何组装一个注册中心?

很多人都不清楚自己找的是Kanban软件还是看板软件

$router和$route的区别

RT thread learning notes (I) -- configure RT thread development environment

0x00007ffd977c04a8 (qt5sqld.dll) (in a.exe): 0xc0000005: an access violation occurred when reading position 0x0000000000000010

Kali view IP address

Successfully transplanted stemwin v5.22 on Shenzhou IV development board
随机推荐
c 语言中宏参数的字符串化跟宏参数的连接
RT-Thread 学习笔记(一)---配置RT-Thread开发环境
微信公众号消息通知 “errcode“:40164,“errmsg“:“invalid ip
面试过程中,面试官是如何考察Rust工程师的水平?
Build ARM embedded development environment
Error[Pe147]: declaration is incompatible with '错误问题
Halcon模板匹配之Shape
IAR sprintf 浮点 在UCOS 总格式化成0.0的问题
鹏哥C语言第六节课
RT thread learning notes (VII) -- open the elmfat file system based on SPI flash (middle)
Flutter TextField设置高度并且自动换行,圆角边框去除下划线
Sword finger offer (twenty): stack containing min function
RT-Thread 学习笔记(三)---用SCons 构建编译环境
在神州IV开发板上为STemWin 5.22加入触屏驱动
Bash shell学习笔记(四)
Wechat official account development obtains openid times error 40029 invalid code solution
display-inline+calc实现左中右布局,中间自适应
104.二叉树的最大深度
访问权限——private,public,protected
RT thread learning notes (V) -- edit, download and debug programs