Android ListView How to Page-load data _android

Source: Internet
Author: User
Tags event listener

Friends who are familiar with Android know that both the microblogging client and the news client are inseparable from the list component, and that the list component is the most important component of the Android data presentation, and we're going to talk about the list component ListView loading data today. In general, an application in the display of large amounts of data, not all the available data will be presented to the user, because this is not only for the server or the client is not a small pressure, therefore, many applications are used in batches of the form of loading to obtain the user's required data. For example: A 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, and then load the next page of data after the user clicks.
Today we'll combine examples to illustrate the process of using ListView to get data.
To create a new Loadmore project, let's take a look at the chart and the final effect:

The left figure contains three layout files, a adapter and an activity, and the right image is the main interface after our operation.
Where Main.xml is the layout file for the main interface, which contains a ListView component with the following code:

<?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 Android's built-in ID named list, because we're going to use listactivity later, and our mainactivity inherits from it.
Then there's the List_item.xml, which is the layout file for a single list item in ListView, as you can see from the effect diagram, where only one TextView component is used, and the 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> 

What happens when we notice that there is a button at the bottom of the list on the right that is different from the other list items? In fact, this button is a view we added at the bottom of the ListView. The ListView component provides two very useful features: You can add a custom view at the top and the bottom. We added a view at the bottom of the ListView to load more data, which corresponds to the Load_more.xml layout file, and the 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= "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> 

Now let's take a 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 List item * @param item * */public void AddItem (String item) {Items.Add (item); 
 } 
}

This listviewadapter is our custom adapter that inherits from Baseadapter, and instantiating this adapter requires a context object to get the Layoutinflater instance and a collection object to act as the adapter's dataset In the GetView method we populate the List_item.xml layout file, complete the data display for each item in the list, and the AddItem method is used to add new data to the dataset when the data is loaded.
Finally, let's take a 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;    The final visual index is private int visibleitemcount; 
  Total number of current window visible items 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 ();  Get ID is the ListView listview.addfooterview (loadmoreview) of the list; 
     
    Set the bottom view of the list initadapter ();        Setlistadapter (adapter);   Automatically sets the adapter Listview.setonscrolllistener (this) for the ListView ID is the list; Add Slide Monitor}/** * Initialize adapter/private void Initadapter () {arraylist<string> items = new Arra 
    Ylist<string> (); 
    for (int i = 0; i < i++) {Items.Add (string.valueof (i + 1)); 
  } adapter = new Listviewadapter (this, items); /** * is called when sliding * * @Override public void onscroll (Abslistview view, int firstvisibleitem, int visibleite 
    Mcount, int totalitemcount) {this.visibleitemcount = VisibleItemCount; 
  Visiblelastindex = Firstvisibleitem + visibleItemCount-1; 
    /** * is called when sliding state is changed * * @Override public void onscrollstatechanged (Abslistview view, int scrollstate) {  int itemslastindex = Adapter.getcount ()-1;The index of the last item in the dataset int lastindex = Itemslastindex + 1; Plus the Loadmoreview item at the bottom if (scrollstate = = Onscrolllistener.scroll_state_idle && Visiblelastindex = = lastindex) 
    {//If it is automatic loading, you can place the code log.i ("Loadmore", "Loading ...") that asynchronously loads the data here; }/** * Click the button event * @param view */public void Loadmore (view view) {Loadmorebutton.settext ("  Loading ... "); Set button text loading handler.postdelayed (new Runnable () {@Override public void run () {L 
         
        Oaddata (); Adapter.notifydatasetchanged (); After the data set changes, notify adapter listview.setselection (Visiblelastindex-visibleitemcount + 1);  Sets the selected item Loadmorebutton.settext ("Load More"); 
  Restore button text}, 2000); 
    /** * Simulate loading data */private void LoadData () {int count = Adapter.getcount (); 
    for (int i = count; i < count +; i++) {Adapter.additem (string.valueof (i + 1)); 
 } 
  } 
}

As the code shows, we get the ListView component when the OnCreate method is invoked, set its bottom view to Loadmoreview, it contains a button that triggers the Loadmore method call when clicked, and when the adapter is set for ListView, A sliding event listener is also set for it, the onscroll is invoked when the slide list is made, and the onscrollstatechanged is invoked when the sliding state changes.
Let's demonstrate this loading process:

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

Finally, we test the slide list to the bottom and release it, and the console prints the following:

We see that the code executes in the IF statement in the Onscrollstatechanged method, so if we want to load it automatically, we can put the load code here.
Let's talk about this today, thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.