Android in the ListView paging load data

Source: Internet
Author: User

Android friends know that, whether it is a microblogging client or news client, is inseparable from the list of components, can say that the list of components is the most important component of Android data presentation, we are going to talk about the list of components of the ListView loading data related content. Generally speaking, an application will not present all the available data to the user when it presents a large amount of data, because this is not a small pressure for both the server and the client, so many applications take the form of batch loading to get the data the user needs. For example, a microblog client may load the next page of data automatically when the user slides to the bottom of the list, or it may place a "load more" button at the bottom, after which the user clicks to load the next page of data.

Let's use the example today to illustrate the process of getting data using a ListView.

To create a new Loadmore project, let's look at the structure diagram and finally:

The diagram on the left contains three layout files, a adapter and an activity, and the image on the right is the main interface after we run it.

Where Main.xml is the layout file of the main interface, it contains a ListView component with the following code:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns: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">    <ListViewAndroid:id= "@id/android:list"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"/></LinearLayout>

Here we refer to the Android built-in ID named list, because we want to use the listactivity, our mainactivity inherit from it.

Then there is list_item.xml, which is the layout file for a single list item in the ListView, where you can see that only one TextView component is used, and the List_item.xml code is as follows:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent">    <TextViewAndroid: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 different from the other list item at the bottom of the list in the right image? In fact, this button is a view we added at the bottom of the ListView. The ListView component provides two useful features that allow you to add a custom view at the top and bottom. Here we add a view at the bottom of the ListView to load more data, which corresponds to the Load_more.xml layout file with the following code:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content">  <ButtonAndroid:id= "@+id/loadmorebutton"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Load More"Android:onclick= "Loadmore"/></LinearLayout>

Let's take a look at our adapter,listviewadapter code below:

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);} @Overridepublic int GetCount () {return items.size ();} @Overridepublic Object getItem (int position) {return items.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view view, ViewGroup parent) {if (view = = null) {view = Inflater.inflate (R.layo Ut.list_item, null);} TextView Text = (TextView) View.findviewbyid (R.id.list_item_text); Text.settext (items.get); return view;} /** * Add List item * @param item */PUBLIC void AddItem (String item) {Items.Add (item);}} 

  

This listviewadapter is our custom adapter, which inherits from Baseadapter, instantiating this adapter requires a context object to get the Layoutinflater instance and a collection object to act as the data set of the adapter In the GetView method we populate the List_item.xml layout file, complete the data display for each item of the list; 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 visible LastIndex = 0;//last visual index private int visibleitemcount;//The total number of visible items in the current window private Listviewadapter adapter;private View Loadmoreview;private Button loadmorebutton;private Handler Handler = new Handler (); @Overridepublic 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 List of listviewlistview.addfooterview (Loadmoreview);//Set list bottomView Initadapter (); Setlistadapter (adapter);//auto-set adapter Listview.setonscrolllistener for the ListView of the list (this);//Add Slide listener}  /** * 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 sliding is called */@Overridepublic void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int Totalitemco UNT) {This.visibleitemcount = Visibleitemcount;visiblelastindex = Firstvisibleitem + visibleItemCount-1;} /** * The sliding state is called */@Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {int itemslastindex = ADAP Ter.getcount ()-Index of the last item of the 1;//DataSet int lastIndex = Itemslastindex + 1;//plus the Loadmoreview item at the bottom if (scrollstate = = Onscrolllistener.scroll_state_idle && Visiblelastindex = = LastIndex) {//If it is auto-loaded, you can place the code that loads the data asynchronously log.i (" Loadmore "," Loading ... ");}} /** * Click Button Event * @param view */public void Loadmore (view view) {Loadmorebutton.setText ("Loading ...");//Set Button text loadinghandler.postdelayed (new Runnable () {@Overridepublic void run () {loaddata (); Adapter.notifydatasetchanged ()///Data set change, notify Adapterlistview.setselection (Visiblelastindex-visibleitemcount + 1);// Set the selected item Loadmorebutton.settext ("Load More");//Recover button text}}, 2000);} /** * Analog load data */private void LoadData () {int count = Adapter.getcount (); for (int i = count; i < count +; i++) {Adapte R.additem (string.valueof (i + 1));}}}

  

As the code shows, we get the ListView component when the OnCreate method is called, set its bottom view to Loadmoreview, which contains a button that triggers the Loadmore method call when clicked, and when the adapter is set for the ListView, The sliding event listener is also set, and the onscroll is called when the list is sliding, and onscrollstatechanged is called when the sliding state changes.

Let's demonstrate this loading process:

, when the button is finished, the load action appears, after loading, as shown in the image on the right, the new data is immediately after the original data. Then we swipe to the bottom and the load button still works:

Finally, we test the slide list to the bottom, then release, and the console prints as follows:

We see that the code in the IF statement in the Onscrollstatechanged method executes, so if we want to load it automatically, we can put the loading code here.

Let's talk about it here today, thank you.

Android in the ListView paging load data

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.