当前位置:网站首页>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
边栏推荐
- Pengge C language sixth class
- 242.有效的字母异位词
- Flutter集成极光推送
- Capture ZABBIX performance monitoring chart with selenium
- Sql Server 之SQL语句对基本表及其中的数据的创建和修改
- RT thread learning notes (I) -- configure RT thread development environment
- [machine learning notes] [face recognition] deeplearning ai course4 4th week programming
- Tutorial of putty
- 2021-08-14 Sanzi chess
- Bash shell学习笔记(七)
猜你喜欢
随机推荐
二叉树的遍历 递归+迭代
ThreadPoolExecutor是怎样执行任务的
toolstrip 去边框
Sql Server 数据库之数据类型
Bash shell学习笔记(三)
微信公众号消息通知 “errcode“:40164,“errmsg“:“invalid ip
Flutter jni混淆 引入.so文件release包闪退
企鹅龙(DRBL)无盘启动+再生龙(clonezilla)网络备份与还原系统
创建EOS账户 Action
Happens-Before原则深入解读
344.反转字符串
10 let operator= return a reference to *this
[leetcode daily question 2021/2/13]448. Find all the missing numbers in the array
Sword finger offer (44): flip the word order sequence
c 语言中宏参数的字符串化跟宏参数的连接
Flutter集成极光推送
c结构体中定义的成员指针赋值与结构体指针作为成员函数参数的使用
nmap弱点扫描结果可视化转换
104. Maximum depth of binary tree
1748.唯一元素的和









