Android-based listview automatically loads data after scrolling to the end

Source: Internet
Author: User

Anyone familiar with Android knows that neither Weibo client nor news client can do without the list component. It can be said that the list component is the most important component for Android data presentation, today we will talk about how the list component listview loads data. Generally, when an application displays a large amount of data, it does not present all the available data to the user, because this is not a small pressure for the server or the client, so, many applications load data in batches to obtain user data. For example, the Weibo client may automatically load the next page of data when the user slides to the bottom of the list, or place a "load more" button at the bottom. After the user clicks the button, the next page of data is loaded.

Today, we will use examples to demonstrate how to use listview to obtain data.

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

 

The left diagram contains three layout files, one adapter and one activity. The right diagram shows the main interface after running.

Here, Main. XML is the layout file of the main interface, which contains a listview component, 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="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 reference the android built-in list ID, because we will use listactivity later, and our mainactivity inherits from it.

Then there is list_item.xml, which is the layout file of a single list item in listview. We can see that only one textview component is used here. 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>

We noticed that there is a button at the bottom of the list in the right figure, which is different from other list items. What is the situation? In fact, this button is a view we added at the bottom of the listview. The listview component provides two practical functions: You can add custom views at the top and bottom. Here we add a view at the bottom of the listview to load more data. This view corresponds to the load_more.xml layout file. 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>

Next, let's take a look at our Adapter. The 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, 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, 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 );}}

The listviewadapter is a custom adapter that inherits from the baseadapter. to instantiate This adapter, you need a context object to obtain the layoutinflater instance and a collection object to act as the dataset of the adapter; in the getview method, we fill in the list_item.xml layout file to display the data of each item in the list. The additem method is used to add new data to the dataset when loading data.

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; private int visiblelastindex = 0; // The final 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 = 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 (); // obtain listviewlistview whose ID is list. addfooterview (loadmoreview); // sets the initadapter () at the bottom of the list; setlistadapter (adapter); // automatically sets the listview adapter for the listview whose ID is list. setonscrolllistener (this); // Add a sliding listener}/*** initialize the 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);}/*** called when sliding */@ overridepublic void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {This. visibleitemcount = visibleitemcount; visiblelastindex = sliding + visibleitemcount-1;}/*** called when the sliding status changes */@ overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {int itemslastindex = adapter. getcount ()-1; // The index int lastindex = itemslastindex + 1 for the last dataset; // Add the loadmoreview item at the bottom if (scrollstate = onscrolllistener. scroll_state_idle & visiblelastindex = lastindex) {// if it is automatically loaded, you can place the code log for Asynchronously loading data here. I ("loadmore", "loading... ") ;}}/*** click button event * @ Param view */Public void loadmore (view) {loadmorebutton. settext ("loading... "); // set the button text loadinghandler. postdelayed (New runnable () {@ overridepublic void run () {loaddata (); adapter. notifydatasetchanged (); // After the dataset changes, the adapterlistview is notified. setselection (visiblelastindex-visibleitemcount + 1); // you can specify loadmorebutton. settext ("load more"); // restore button text }}, 2000);}/*** simulate loading 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 the oncreate method is called, we obtain the listview component and set its bottom view to loadmoreview. It contains a button, which triggers the loadmore method call, in addition, when the adapter is set for the listview, a sliding event listener is set for it. onscroll is called when the sliding list is set, and onscrollstatechanged is called when the sliding status is changed.

Let's demonstrate the loading process:

 

After clicking the button, the loading action is displayed. As shown in the right figure after loading, the new data is immediately following the original data. Then we slide to the bottom and the load button will still work:

Finally, let's test the slide list to the bottom and release it. The console prints the following:

 

 

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.