Home  >  Article  >  Java  >  Android interface data lazy loading implementation code

Android interface data lazy loading implementation code

高洛峰
高洛峰Original
2016-12-27 15:16:181534browse

Everyone will make a discovery when using mobile news clients. Most news clients will classify news, such as headlines, entertainment, sports, technology, etc. How to implement this interface? This is actually very simple to implement. It is to implement the switching of multiple ViewPages in a Fragment, then put a TabLayout on top of the ViewPage, and associate them to achieve the linkage effect. If you feel unclear, I can write a blog specifically about putting multiple ViewPages in Fragments in the future. Today, I mainly introduce how to implement lazy loading of the interface, that is, Fragments. Then, everyone will be surprised. Since it is loaded directly on the loading interface, why do we still use lazy loading? This requires talking about the benefits of lazy loading. As mentioned above, the principle of most news clients to implement various news switching is to store multiple ViewPages in one Fragment. If the data in all ViewPages is loaded after entering the program, it will undoubtedly increase the running time of the APP. The burden, and lazy loading can realize that the viewpage in the fragment only preloads one interface when the program starts, waits until it slides to the next interface, then loads the data of the next viewpage, and implements the loading interface cache, and switches to this interface next time It will no longer be reloaded. Okay, let’s explain clearly why lazy loading is used, let’s get to the main topic today.

Step one: Customize a fragment and let it inherit Fragment
1. Override the setUserVisibleHint method
2. Define an abstract method lazyInitData()

package com.jereh.jinritoutiao.fragmentdemo.fragment;
 
import android.support.v4.app.Fragment;
 
/**
 * Created by zhangdi on 2016/8/8.
 */
public abstract class BaseFragment extends Fragment {
protected boolean isVisible = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
//加载数据
isVisible = true;
   lazyInitData();
  }else {
isVisible = false;
  }
 }
public abstract void lazyInitData();
}

Step 2: Define another fragment to inherit the fragment
just defined. 1. First define a global variable to save the status of the fragment (this step is prepared for the cache interface). Define two boolean variables to indicate that the fragment's view control has been Be ready and whether the current fragment has loaded data
2. Determine whether the status of the fragment is empty. If it is empty, generate a new interface
3. Rewrite the lazyInitData() method of the parent class to implement lazy loading

/**
 * A simple {@link Fragment} subclass.
 */
public class NetNewsFragment extends BaseFragment {
  //定义一个全局变量用来保存Fragment的状态
  private View v;
  //listview展示的数据
  private List<NetNews> mData;
  private PullToRefreshListView lv;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String u= getArguments().getString("api");
    if(!TextUtils.isEmpty(u)){
      url = u;
  }
 }
 
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        if(v==null) {
          //将布局关联起来
          v = inflater.inflate(R.layout.fragment_net_news, container, false);
          //找到ViewPage
          lv = (PullToRefreshListView) v.findViewById(R.id.lv01);
          mData = new ArrayList<>();
          //初始化适配器
          adapter = new NetNewsAdapter(mData, getActivity());
          lv.setAdapter(adapter);
          //界面已经准备完毕
          isPrepared = true;
     (new android.os.Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
     lazyInitData();
      }
       },200);
       }
        return v;
  }
 
  /**
  * 初始化Fragment数据的方法,实现懒加载
   */
  @Override
  public void lazyInitData() {
    if (isPrepared&&isVisible&&isFirst){
        lv.setRefreshing();
   VolleyUtil.get(url+"?num=20&page="+page)
    .setCallBack(new NetCallBack())
    .build()
    .addRequestHeader("apikey", Constants.API_KEY)
    .start();
    isFirst = false;
  }
 }

In order to highlight the lazy loading code, I have omitted the style monitoring of PullToListView, and the method here (new android.os.Handler()).postDelayed(new Runnable()) is Asynchronous loading is implemented using multi-threading, so that when initializing the layout, there is time to generate interface components and then load data.

At this point, the purpose of lazy loading of interface (Fragment) data in Android has been achieved. If you want to switch between multiple interfaces in the future and the data requires network requests, it is recommended to use lazy loading.

Okay, that’s it for the introduction to lazy loading.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to Android interface data lazy loading implementation code, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn