Home Java javaTutorial Android interface data lazy loading implementation code

Android interface data lazy loading implementation code

Dec 27, 2016 pm 03:16 PM

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();
}
Copy after login

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;
  }
 }
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles