Implementation of the Advanced Android UI page load of the ListView

Source: Internet
Author: User

The previous blog post and everyone shared the dropdown refresh, which is a very good way to operate the user experience. Sina's meager use is typical of this approach.

There is also a problem, when the user from the network to read the meager time, if all of a sudden load the user unread this will take a long time, resulting in a bad user experience, while the content of a screen is not enough to display so much content. At this point, we need to use another function, that is the page of the ListView. By paging through the data load, the user can see how much to load.

Usually this is also divided into two ways, one is to set a button, the user click to load. The other is automatically loaded when the user slides to the bottom. Today I will share with you the implementation of this feature.

First, write an XML file, Moredata.xml, that defines the view that is placed at the bottom of the ListView:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical" > <Button Android:id= "@+id/bt_load"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Load more Data"/> <ProgressBar Android:id= "@+id/pg"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal"android:visibility= "Gone"/></linearlayout>

You can see that it is a button and a progress bar. Because only a demo is done here, it is easy to handle it by setting the control's visibility, displaying the button when it is not loaded, and displaying the progress bar when loaded.

Write a item.xml, everyone should be very familiar with it. The view used to define each item of the ListView.

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical" > <TextView Android:id= "@+id/tv_title"android:textsize= "20SP"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margintop= "5DP"/> <TextView android:textsize= "12SP"Android:id= "@+id/tv_content"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margintop= "5DP"/></linearlayout>

Main.xml is not posted, the entire main interface is a ListView.

Look directly at the activity code to achieve the paging effect inside.

 Packagecom.notice.moredate;Importjava.util.ArrayList;ImportJava.util.HashMap;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.AbsListView;ImportAndroid.widget.AbsListView.OnScrollListener;ImportAndroid.widget.Button;ImportAndroid.widget.ListView;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.SimpleAdapter;ImportAndroid.widget.Toast; Public classMoredatelistactivityextendsActivityImplementsOnscrolllistener {//adapter of the ListView    PrivateSimpleadapter Msimpleadapter; PrivateListView LV; PrivateButton BT; PrivateProgressBar pg; PrivateArraylistlist; //ListView Bottom View    PrivateView Moreview; PrivateHandler Handler; //set a maximum number of data bars, which is no longer loaded    Private intMaxdatenum; //index of the last visible entry    Private intLastvisibleindex; /**Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                        Setcontentview (R.layout.main); Maxdatenum= 22;//set maximum number of data barsLV=(ListView) Findviewbyid (r.id.lv); //instantiate the bottom of the layoutMoreview = Getlayoutinflater (). Inflate (R.layout.moredate,NULL); BT=(Button) Moreview.findviewbyid (r.id.bt_load); PG=(ProgressBar) Moreview.findviewbyid (R.ID.PG); Handler=NewHandler (); //use map to load data, initialize 10 of dataList =NewArraylist();  for(inti = 0; I < 10; i++) {HashMap<string, string> map =NewHashmap<string, string>(); Map.put ("Itemtitle", "first" + i + "Row header"); Map.put ("Itemtext", "first" + i + "line contents");        List.add (map); }        //Instantiate SimpleadapterMsimpleadapter =NewSimpleadapter ( This, List, R.layout.item,NewString[] {"Itemtitle", "Itemtext" },                New int[] {r.id.tv_title, r.id.tv_content}); //with the bottom view, be careful to put it in front of the Setadapter methodLv.addfooterview (Moreview);        Lv.setadapter (Msimpleadapter); //Binding ListenersLv.setonscrolllistener ( This); Bt.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {pg.setvisibility (view.visible);//make progress bar visibleBt.setvisibility (View.gone);//button is not visiblehandler.postdelayed (NewRunnable () {@Override Public voidrun () {loadmoredate ();//load More Databt.setvisibility (view.visible);                        Pg.setvisibility (View.gone); Msimpleadapter.notifydatasetchanged ();//notifies the ListView to refresh Data                    }                }, 2000);    }        }); }    Private voidloadmoredate () {intCount =Msimpleadapter.getcount (); if(Count + 5 <maxdatenum) {            //Load 5 strips at a time             for(inti = count; I < count + 5; i++) {HashMap<string, string> map =NewHashmap<string, string>(); Map.put ("Itemtitle", "added" + i + "Row header"); Map.put ("Itemtext", "Add new" + i + "line content");            List.add (map); }        } Else {            //The data is less than 5 records             for(inti = count; i < Maxdatenum; i++) {HashMap<string, string> map =NewHashmap<string, string>(); Map.put ("Itemtitle", "added" + i + "Row header"); Map.put ("Itemtext", "Add new" + i + "line content");            List.add (map); } }} @Override Public voidOnscroll (Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) {        //calculates the index of the last visible entryLastvisibleindex = Firstvisibleitem + visibleItemCount-1; //all entries are equal to the maximum number of bars, then the view at the bottom is removed        if(Totalitemcount = = Maxdatenum + 1) {Lv.removefooterview (Moreview); Toast.maketext ( This, "The data is all loaded, no more data!" ", Toast.length_long). Show (); }} @Override Public voidOnscrollstatechanged (Abslistview view,intscrollstate) {        //automatically load after sliding to the bottom, judging that the ListView has stopped scrolling and the last visible entry equals the adapter entry        if(Scrollstate = =Onscrolllistener.scroll_state_idle&& Lastvisibleindex = =Msimpleadapter.getcount ()) {            //load automatically when sliding to the bottom//pg.setvisibility (view.visible); //bt.setvisibility (View.gone); //handler.postdelayed (New Runnable () {//            //@Override//Public void Run () {//loadmoredate (); //bt.setvisibility (view.visible); //pg.setvisibility (View.gone); //msimpleadapter.notifydatasetchanged (); // }            //            //}, +);        }    }    }

By commenting, it should be easy to understand. Here's a simple explanation. The first thing to note is that the Addfootview method must be before the Setadapter method, otherwise it will be invalid. The Addfootview method adds a view to the bottom of the ListView, in this case the button plus ProgressBar view. When the user taps the button, calls the Loadmoredate method, binds more data to the ListView, notifies the ListView refresh by Adapter's Notifydatasetchanged method, and displays the data just added.

This handler asynchronously delays 2 second operation, mimicking the loading process. The ListView also binds the Onscrolllistener listener, and implements the Onscroll and Onscrollstatechanged methods. In the latter method, we know that the ListView has stopped scrolling and the last visible entry equals the adapter entry, knowing that the user has slipped to the bottom and loaded automatically, and that the code has commented out this part of the code, and you can try it yourself.

The code also adds a Maxdatenum variable to record the maximum number of data. That is to say, network or other places altogether data. After the user has finished loading the data, the Onscroll method is used to remove the bottom view of the ListView and not allow the load to continue. At the same time, in the Loadmoredate method, the maximum amount of data is also manipulated to determine the number of loads. (Load the remaining 5 by default, less than 5).

Look under:

It's so much to write about, but in general it's very simple, but it's a really useful effect. Welcome to Message exchange.

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.