Android Create paging with ListView

Create paging with ListView

Android familiar friends all know, whether it is microblogging client or news client, are inseparable from the list of components, it can be said the list of components is the most important aspect of Android data presentation components, we have to talk about the list of components ListView today Load related content data. Generally speaking, when an application to show large amounts of data, not all of the available data are presented to the user, because it regardless of the server or the client for it is no small pressure, therefore, many applications are based on points in the form of batch loaded to get the data you need. For example: microblogging client may automatically loads next data when the user slides to the bottom of the list, it may be placed at the bottom of a "load more" button, the user clicked, loads next data.
Today, we combine the use of examples to demonstrate what ListView data acquisition process.
Create a loadmore project, we look at the charts and the final image:




The left contains three layout file, a Adapter and a Activity, right after we run the main interface.
Wherein, main.xml is the main interface layout file that contains a ListView components, as follows:
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:paddingLeft="3dp" 
    android:paddingRight="3dp"> 
    <ListView 
        android:id="@id/android:list" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"/> 
</ LinearLayout> 

Here we refer to the Android built-in named list of id, because we want to use later to ListActivity, our MainActivity inherit it.
Then is list_item.xml, it is the ListView layout file a single list item, from renderings can be seen here only to use a TextView component, list_item.xml code is as follows:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <TextView 
        android:id="@+id/list_item_text" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:gravity="center" 
        android:textSize="20sp" 
        android:paddingTop="10dp" 
        android:paddingBottom="10dp"/> 
</ LinearLayout> 


We note that the list in the bottom right there is a button Unlike other list items, this is what happens? In fact, this button is a view that we added in the bottom of the ListView. ListView component provides two very useful features that you can add custom views at the top and bottom. We here at the bottom of the ListView adds a view to load more data, this view corresponds load_more.xml layout files, as follows:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content"> 
  <Button 
        android:id="@+id/loadMoreButton" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="load more" 
        android:onClick="loadMore"/> 
</ LinearLayout> 

Next we look at our Adapter, ListViewAdapter code is as follows:

package com.scott.loadmore; 
 
import java.util.List; 
 
import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 
 
public class ListViewAdapter extends BaseAdapter { 
    private List<String> items; 
    private LayoutInflater inflater; 
     
    public ListViewAdapter(Context context, List<String> items) { 
        this.items = items; 
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);       
    } 
      
    @Override 
    public  int  getCount () { 
        return items.size(); 
    } 
 
    @Override 
    public Object getItem(int position) { 
        return items.get(position); 
    } 
 
    @Override 
    public long getItemId(int position) { 
        return position; 
    } 
 
    @Override 
    public View getView(int position, View view, ViewGroup parent) { 
        if (view == null) { 
            view = inflater.inflate(R.layout.list_item, null); 
        } 
        TextView text = (TextView) view.findViewById(R.id.list_item_text); 
        text.setText(items.get(position)); 
        return view; 
    } 
     
    /**
     * Add a list item
     * @param item
     * / 
    public void addItem(String item) { 
        items.add(item); 
    } 

This ListViewAdapter is our custom adapter, it inherits from BaseAdapter, instantiate this adapter requires a Context object to get LayoutInflater instance and to act as a collection object adapter data sets; we filled in getView method list_item.xml layout files, complete list Each data display; addItem method is used when loading data set to add new data to the data.
Finally, we look at MainActivity:

package com.scott.loadmore; 
 
import java.util.ArrayList; 
 
import android.app.ListActivity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.util.Log; 
import android.view.View; 
import android.widget.AbsListView; 
import android.widget.AbsListView.OnScrollListener; 
import android.widget.Button; 
import android.widget.ListView; 
 
public class MainActivity extends ListActivity implements OnScrollListener { 
    private ListView listView; 
    Private  int  visibleLastIndex =  0 ;    // last visible item index 
    Private  int  visibleItemCount;        // total number of items in the current window visible 
    private ListViewAdapter adapter; 
    private View loadMoreView; 
    private Button loadMoreButton; 
    private Handler handler = new Handler(); 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null); 
        loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton); 
 
        listView = getListView();              
         
        listView.addFooterView (loadMoreView);    // set the bottom of the list view 
 
        initAdapter (); 
         
        setListAdapter (Adapter);                 // id is automatically set the adapter list of ListView 
         
        listView.setOnScrollListener ( this );      // add listener slide 
    } 
     
    /**
     * Initialize adapter
     * / 
    private  void  initAdapter () { 
        ArrayList<String> items = new ArrayList<String>(); 
        for (int i = 0; i < 10; i++) { 
            items.add(String.valueOf(i + 1)); 
        } 
        adapter = new ListViewAdapter(this, items); 
    } 
 
    /**
     * When the slide is called
     * / 
    @Override 
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 
        this.visibleItemCount = visibleItemCount; 
        visibleLastIndex = firstVisibleItem visibleItemCount + -  1 ; 
    } 
 
    /**
     * When the slide is called the status change
     * / 
    @Override 
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
        int  itemsLastIndex = adapter.getCount () -  1 ;     // index of the last item of the data set 
        int  lastIndex = itemsLastIndex +  1 ;              // add loadMoreView item at the bottom 
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { 
            // If it is automatically loaded, you can place the code to load data asynchronously here 
            Log.i("LOADMORE", "loading..."); 
        } 
    } 
     
    /**
     * Click the button event
     * @param view
     * / 
    public void loadMore(View view) { 
        loadMoreButton.setText("loading...");  
        handler.postDelayed(new Runnable() { 
            @Override 
            public void run() { 
                 
                loadData (); 
                 
                adapter.notifyDataSetChanged ();  // data set after the change, notify adapter 
                listView.setSelection (visibleLastIndex - visibleItemCount +  1 );  // Set the selected item 
                  
                loadMoreButton.setText("load more");  
            } 
        },    2000);
    } 
     
    /**
     * Analog load data
     * / 
    private  void  loadData () { 
        int count = adapter.getCount(); 
        for (int i = count; i < count + 10; i++) { 
            adapter.addItem(String.valueOf(i + 1)); 
        } 
    } 

As shown in the code, when we get onCreate method is invoked listView assembly, set the bottom view of the loadMoreView, which includes a button that will trigger clicked loadMore method call, the other at the end of listView set the adapter, but also to set up Sliding event listener, when the slide list onScroll will be called when the slide status change onScrollStateChanged will be called.
Let's show you the loading process:




As shown, when finished click on the button, there loading operation, the new data immediately after the original data is loaded after completion as shown at right. Then we slide in the end portion, the Load button still work:





Share this

Related Posts

First