ListView Paging Load Data in Android

Original address: http://blog.csdn.net/liuhe688/article/details/6852523


be familiar with Android As you all know, no matter the micro-blog client or the news client, it can not be separated from the list component. It can be said that the list component is the most important component in Android data presentation. Today we will talk about the list component ListView loading data related content. Generally speaking, when an application presents a large amount of data, it will not present all available data to users, because this is not a small pressure for both the server and the client. Therefore, many applications use batch loading to obtain the data users need. For example, the microblog client may automatically load the next page of data when the user slides to the bottom of the list, or it may place a "Load More" button at the bottom to load the next page of data after the user clicks.

Let's show you how to use ListView to get data with examples today.

Create a new loadmore project. Let's take a look at the structure diagram and the final effect diagram.

 

The left figure contains three layout files, an Adapter and an Activity, and the right one is our main interface after running.

The main.xml is the layout file of the main interface, which contains a ListView component. The code is as follows:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:paddingLeft="3dp"  
  7.     android:paddingRight="3dp">  
  8.     <ListView  
  9.         android:id="@id/android:list"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"/>  
  12. </LinearLayout>  
Here we refer to Android's built-in id called list, because we're going to use ListActivity later, and our MainActivity inherits it.

Then there is list_item.xml, which is the layout file of a single list item in ListView. As you can see from the rendering, only one TextView component is used here. The list_item.xml code is as follows:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent">  
  6.     <TextView  
  7.         android:id="@+id/list_item_text"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="fill_parent"  
  10.         android:gravity="center"  
  11.         android:textSize="20sp"  
  12.         android:paddingTop="10dp"  
  13.         android:paddingBottom="10dp"/>  
  14. </LinearLayout>  
We noticed that there is a button at the bottom of the list in the right figure that is different from other list items. What is the situation? In fact, this button is a view we added at the bottom of ListView. The ListView component provides two very useful functions: you can add custom views at the top and bottom. Here we add a view at the bottom of ListView to load more data. This view corresponds to the load_more.xml layout file. The code is as follows:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="vertical"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="wrap_content">  
  7.   <Button  
  8.         android:id="@+id/loadMoreButton"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="load more"  
  12.         android:onClick="loadMore"/>  
  13. </LinearLayout>  
Next, let's look at our Adapter, ListViewAdapter code as follows:

  1. package com.scott.loadmore;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.content.Context;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9. import android.widget.BaseAdapter;  
  10. import android.widget.TextView;  
  11.   
  12. public class ListViewAdapter extends BaseAdapter {  
  13.     private List<String> items;  
  14.     private LayoutInflater inflater;  
  15.       
  16.     public ListViewAdapter(Context context, List<String> items) {  
  17.         this.items = items;  
  18.         inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        
  19.     }  
  20.       
  21.     @Override  
  22.     public int getCount() {  
  23.         return items.size();  
  24.     }  
  25.   
  26.     @Override  
  27.     public Object getItem(int position) {  
  28.         return items.get(position);  
  29.     }  
  30.   
  31.     @Override  
  32.     public long getItemId(int position) {  
  33.         return position;  
  34.     }  
  35.   
  36.     @Override  
  37.     public View getView(int position, View view, ViewGroup parent) {  
  38.         if (view == null) {  
  39.             view = inflater.inflate(R.layout.list_item, null);  
  40.         }  
  41.         TextView text = (TextView) view.findViewById(R.id.list_item_text);  
  42.         text.setText(items.get(position));  
  43.         return view;  
  44.     }  
  45.       
  46.     /** 
  47.      * Add List Items 
  48.      * @param item 
  49.      */  
  50.     public void addItem(String item) {  
  51.         items.add(item);  
  52.     }  
  53. }  
This ListView Adapter is our custom adapter, which inherits from BaseAdapter. To instantiate this adapter, we need a Context object to get a LayoutInflate instance and a collection object to act as the data set of the adapter. In the getView method, we fill in the list_item.xml layout file to complete the data display of each item in the list. The addItem method is used to add new data to the data set when loading data.

Finally, let's take a look at MainActivity:

  1. package com.scott.loadmore;  
  2.   
  3. import java.util.ArrayList;  
  4.   
  5. import android.app.ListActivity;  
  6. import android.os.Bundle;  
  7. import android.os.Handler;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10. import android.widget.AbsListView;  
  11. import android.widget.AbsListView.OnScrollListener;  
  12. import android.widget.Button;  
  13. import android.widget.ListView;  
  14.   
  15. public class MainActivity extends ListActivity implements OnScrollListener {  
  16.     private ListView listView;  
  17.     private int visibleLastIndex = 0;   //Final Visual Item Index  
  18.     private int visibleItemCount;       //Total number of visible items in the current window  
  19.     private ListViewAdapter adapter;  
  20.     private View loadMoreView;  
  21.     private Button loadMoreButton;  
  22.     private Handler handler = new Handler();  
  23.   
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.main);  
  28.           
  29.         loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);  
  30.         loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);  
  31.   
  32.         listView = getListView();               //Getting ListView whose id is list  
  33.           
  34.         listView.addFooterView(loadMoreView);   //Setting the bottom view of the list  
  35.   
  36.         initAdapter();  
  37.           
  38.         setListAdapter(adapter);                //Automatically set the adapter for ListView with id as list  
  39.           
  40.         listView.setOnScrollListener(this);     //Add Sliding Monitor  
  41.     }  
  42.       
  43.     /** 
  44.      * Initialization adapter 
  45.      */  
  46.     private void initAdapter() {  
  47.         ArrayList<String> items = new ArrayList<String>();  
  48.         for (int i = 0; i < 10; i++) {  
  49.             items.add(String.valueOf(i + 1));  
  50.         }  
  51.         adapter = new ListViewAdapter(this, items);  
  52.     }  
  53.   
  54.     /** 
  55.      * Called when sliding 
  56.      */  
  57.     @Override  
  58.     public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {  
  59.         this.visibleItemCount = visibleItemCount;  
  60.         visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  
  61.     }  
  62.   
  63.     /** 
  64.      * Called when the sliding state changes 
  65.      */  
  66.     @Override  
  67.     public void onScrollStateChanged(AbsListView view, int scrollState) {  
  68.         int itemsLastIndex = adapter.getCount() - 1;    //Index of the Last Item of Data Set  
  69.         int lastIndex = itemsLastIndex + 1;             //Add the loadMoreView item at the bottom  
  70.         if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {  
  71.             //If it's automatic loading, you can put asynchronous loading data code here.  
  72.             Log.i("LOADMORE""loading...");  
  73.         }  
  74.     }  
  75.       
  76.     /** 
  77.      * Click on the button event 
  78.      * @param view 
  79.      */  
  80.     public void loadMore(View view) {  
  81.         loadMoreButton.setText("loading...");   //Set the button text load  
  82.         handler.postDelayed(new Runnable() {  
  83.             @Override  
  84.             public void run() {  
  85.                   
  86.                 loadData();  
  87.                   
  88.                 adapter.notifyDataSetChanged(); //Notify adapter when the data set changes  
  89.                 listView.setSelection(visibleLastIndex - visibleItemCount + 1); //Setting Selected Items  
  90.                   
  91.                 loadMoreButton.setText("load more");    //Recovery button text  
  92.             }  
  93.         }, 2000);  
  94.     }  
  95.       
  96.     /** 
  97.      * Simulated Loading Data 
  98.      */  
  99.     private void loadData() {  
  100.         int count = adapter.getCount();  
  101.         for (int i = count; i < count + 10; i++) {  
  102.             adapter.addItem(String.valueOf(i + 1));  
  103.         }  
  104.     }  
  105. }  
As shown in the code, when the onCreate method is invoked, we get the listView component and set its bottom view to loadMoreView, which contains a button that triggers the loadMore method call when clicked. In addition, when the adapter is set up for the listView, we set a sliding event listener for it. When the list is sliding, onScroll is tuned. With this, onScrollStateChanged is invoked when the sliding state changes.

Let's demonstrate the loading process:

 

As shown in the figure, when the button is clicked, the loading action occurs. After loading, as shown in the right figure, the new data is immediately after the original data. Then we slide to the bottom and the load button still works:


Finally, we test Click on the bottom of the sliding list and release it. The console prints as follows:


We see the code executed in the if statement in the onScrollStateChanged method, so if we want to load automatically, we can put the load code here.

Today I'm going to start with this. Thank you.

Keywords: Android xml encoding Java

Added by HAN! on Wed, 10 Jul 2019 03:09:04 +0300