Android-based ListView uses OnScrollListener to load data by PAGE

Source: Internet
Author: User

Android-based ListView uses OnScrollListener to load data by PAGE

In the previous blog, I shared with you the pull-down refresh, which is a very good operation method for user experience. Sina meager is a typical use of this method.

There is another problem. When users read meager data from the network, it will take a long time to load all the meager data that the users have not read, resulting in poor user experience, at the same time, the content on one screen is insufficient to display so much content. At this time, we need to use another function, that is, pagination of listview. You can load data in multiple parts by page.

This is usually divided into two ways, one is to set a button, the user clicks load. The other is automatic loading when the user slides to the bottom. Today, I will share with you the implementation of this function.

First, write an xml file named moredata. xml, which defines the view placed at the bottom of the listview:

 
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "vertical">
Android: id = "@ + id/bt_load"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "loading more data"/>
Android: id = "@ + id/pg"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_gravity = "center_horizontal"
Android: visibility = "gone"
/>

A button and a progress bar are displayed. This is a simple demonstration. By setting the visibility of the control, the button is displayed when the control is not loaded, and the progress bar is displayed when the control is loaded.

You should be familiar with writing an item. xml file. Defines the view of each item in the listview.

 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

android:id="@+id/tv_title"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
android:textSize="12sp"
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>

Main. xml will not be pasted, and the entire main interface will be a listview.

Let's take a look at the Activity code and implement the paging effect in it.

Package com. notice. moredate;

Import java. util. ArrayList;
Import java. util. HashMap;

Import android. app. Activity;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. AbsListView;
Import android. widget. AbsListView. OnScrollListener;
Import android. widget. Button;
Import android. widget. ListView;
Import android. widget. ProgressBar;
Import android. widget. SimpleAdapter;
Import android. widget. Toast;

Public class MoreDateListActivity extends Activity implements OnScrollListener {

// ListView Adapter
Private SimpleAdapter mSimpleAdapter;
Private ListView lv;
Private Button bt;
Private ProgressBar pg;
Private ArrayList > List;
// View at the bottom of the ListView
Private View moreView;
Private Handler handler;
// Set the maximum number of data entries. If the number is exceeded, it is no longer loaded.
Private int MaxDateNum;
// Index of the last visible entries
Private int lastVisibleIndex;

/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );


MaxDateNum = 22; // you can specify the maximum number of data entries.

Lv = (ListView) findViewById (R. id. lv );

// Instantiate the bottom Layout
MoreView = getLayoutInflater (). inflate (R. layout. moredate, null );

Bt = (Button) moreView. findViewById (R. id. bt_load );
Pg = (ProgressBar) moreView. findViewById (R. id. pg );
Handler = new Handler ();

// Use map to load data and initialize 10 data records
List = new ArrayList > ();
For (int I = 0; I <10; I ++ ){
HashMap Map = new HashMap ();
Map. put ("ItemTitle", "th" + I + "Row title ");
Map. put ("ItemText", "th" + I + "Row content ");
List. add (map );
}
// Instantiate SimpleAdapter
MSimpleAdapter = new SimpleAdapter (this, list, R. layout. item,
New String [] {"ItemTitle", "ItemText "},
New int [] {R. id. TV _title, R. id. TV _content });
// Add the bottom View, which must be placed before the setAdapter method.
Lv. addFooterView (moreView );
Lv. setAdapter (mSimpleAdapter );
// Bind the listener
Lv. setOnScrollListener (this );

Bt. setOnClickListener (new OnClickListener (){

@ Override
Public void onClick (View v ){
Pg. setVisibility (View. VISIBLE); // you can View the progress bar.
Bt. setVisibility (View. GONE); // The button is invisible.

Handler. postDelayed (new Runnable (){

@ Override
Public void run (){
LoadMoreDate (); // load more data
Bt. setVisibility (View. VISIBLE );
Pg. setVisibility (View. GONE );
MSimpleAdapter. notifyDataSetChanged (); // notifies listView to refresh data
}

},2000 );
}
});

}

Private void loadMoreDate (){
Int count = mSimpleAdapter. getCount ();
If (count + 5 <MaxDateNum ){
// Load 5 entries each time
For (int I = count; I <count + 5; I ++ ){
HashMap Map = new HashMap ();
Map. put ("ItemTitle", "added" + I + "Row title ");
Map. put ("ItemText", "added" + I + "Row content ");
List. add (map );
}
} Else {
// There are already fewer than 5 data records
For (int I = count; I <MaxDateNum; I ++ ){
HashMap Map = new HashMap ();
Map. put ("ItemTitle", "added" + I + "Row title ");
Map. put ("ItemText", "added" + I + "Row content ");
List. add (map );
}
}

}

@ Override
Public void onScroll (AbsListView view, int firstVisibleItem,
Int visibleItemCount, int totalItemCount ){
// Calculate the index of the last visible entry
LastVisibleIndex = firstVisibleItem + visibleItemCount-1;

// If all entries are equal to the maximum number of entries, the View at the bottom is removed.
If (totalItemCount = MaxDateNum + 1 ){
Lv. removeFooterView (moreView );
Toast. makeText (this, "data is fully loaded, no more data! ", Toast. LENGTH_LONG). show ();
}

}

@ Override
Public void onScrollStateChanged (AbsListView view, int scrollState ){
// Automatically load after sliding to the bottom to determine if the listview has stopped scrolling and the last visible entry is equal to the adapter entry
If (scrollState = OnScrollListener. SCROLL_STATE_IDLE
& LastVisibleIndex = mSimpleAdapter. getCount ()){
// Automatically loaded 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. yydatasetchanged ();
//}
//
// }, 2000 );

}

}

}

Through comments, you should be easy to understand. Here we will make a simple analysis. Note 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 example, it is the view of the Button and progressbar. When you click the button, call the loadmoreDate method to bind more data to the listview, and notify the listview to refresh by using the notifyDataSetChanged method of the adapter to display the newly added data.

Handler is used to asynchronously delay the operation for 2 seconds to simulate the loading process. Meanwhile, listview is bound to the onScrollListener listener and implements the onScroll and onScrollStateChanged methods. In the latter method, we can know that the user has slipped to the bottom and loaded automatically by judging that the listview has stopped scrolling and the last visible entry is equal to the adapter entry, the Code has commented out this part of the code. You can try it yourself.

The Code also adds a MaxDateNum variable to record the maximum amount of data. That is to say, the total data of the network or other places. The onScroll method is used to determine whether a user can load the data and remove the view at the bottom of the listview. In addition, the loadmoreDate method also performs operations on the maximum data volume to determine the number of loads. (Five items are loaded by default. If there are less than five items, the remaining items are loaded ).

See:

Writing so much is still very simple in general, but it is indeed a very useful effect. You are welcome to leave a message.

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.