- After the concept is clear, the specific realization of the part arrived. Here the pull-down loading effect (personal feeling is very good, concise and clear), probably need the following several steps:
- first-first builds the bottom load layout when the pull-down is loaded (named View_more here)
- Second-gets the data and sets the adapter for the ListView; After setting the adapter, call the method:
listView.addFooterView(view_more);// TODO 添加底部记载布局 Add the bottom load layout to the bottom of the ListView. Finally, set the slide listener on the ListView: listView.setOnScrollListener(this);// TODO listView这是滑动监听 and override the related method:
public void onScrollStateChanged(AbsListView view, int scrollState) {}One of the public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {} two overriding methods is to monitor the sliding state of the ListView and the other is to monitor the slide of the ListView.
- third-when the swipe listener is set up, in the two overridden methods, determine if the ListView is sliding to the bottom and stops sliding (that is, the slide state is stopped sliding). If this condition is met at this point, more data will be loaded. When the data is loaded, the data source is refreshed, and more data appears at the bottom.
- fourth-finally when the data is all loaded, remove the bottom load layout view_more added in the second step, calling the method:
listView.removeFooterView(view_more);// TODO 移除底部的加载布局
The following code is written in step-by-step implementation:
- 1, first prepare a bottom load layout, named View_more
<?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" android:layout_width="Match_parent"android:layout_height="80DP"Android : Background="#8888" > <textview android:id = "@+id/tv_load" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerinparent =< Span class= "Hljs-value" > "true" android:text = "Loading ..." android:textsize = "14SP" android:visibility = "visible" /> <progressbar android:id< /span>= "@+id/progressbar" style = android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_ centervertical = "true" android:layout_ Toleftof = "@id/tv_load" android:padding = "10DP" android:visibility = "visible" /> </relativelayout>
A very simple layout that shows a progress bar and a text control.
- Second, set the data for the ListView and set the slide monitor, set it up to determine whether to slide to the bottom of the ListView and stop sliding, if so load more data:
PackageCom.example.drop_down_load;ImportJava.util.ArrayList;ImportJava.util.List;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.AbsListView;ImportAndroid.widget.AbsListView.OnScrollListener;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ListView;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public class mainactivity extends Activity implements Onscrolllistener { PrivateListView ListView;Private intTotalCount;//Data total number of bars Privatelist<string> lists =NewArraylist<string> ();PrivateArrayadapter<string> adapter;//Create handler to receive messages and process messages PrivateHandler Handler =NewHandler () { Public void Handlemessage(Android.os.Message msg) {Switch(msg.what) { Case 0://Create adapteradapter =NewArrayadapter<string> (mainactivity. ThisAndroid. R.layout.simple_list_item_1, lists);//Set adapterListview.setadapter (adapter);//Add bottom load layoutListview.addfooterview (View_more);//Set monitoringSetlisteners (); Break; } }; };PrivateView View_more;PrivateProgressBar PB;PrivateTextView Tvload;Private intLastvisibleindex;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Control initializationInitviews ();//Initialize dataInitData (); }Private void InitData() {//Analog network request for data, get 15 records at a time NewThread () { Public void Run() {Try{TotalCount = -;//Assuming that there are 100 data, the future interface can get this value for(inti =0; I < the; i++) {Lists.add ("Data"+ (i +1)); }//Send message to handler update UI, child thread not to update UIMessage message =NewMessage (); Message.what =0; Handler.sendmessage (message); }Catch(Exception e) {E.printstacktrace (); } }; }.start (); }Private void setlisteners() {if(TotalCount > the) {//ListView Set Slide Simple monitorListview.setonscrolllistener ( This); }Else{//If the total number of data is less than or equal to 15, remove the bottom loading layout directly and no more data will be loadedListview.removefooterview (View_more); } }Private void initviews() {listview = (ListView) Findviewbyid (R.id.listview);//Build bottom load LayoutView_more = (View) getlayoutinflater (). Inflate (R.layout.view_more,NULL);//progress barPB = (ProgressBar) View_more.findviewbyid (R.id.progressbar);//"Loading ..." Text controlTvload = (TextView) View_more.findviewbyid (r.id.tv_load); }/** * Monitor the change in the sliding state of the ListView * / @Override Public void onscrollstatechanged(Abslistview view,intScrollstate) {LOG.E ("TAG","Lastvisibleindex ="+ Lastvisibleindex); LOG.E ("TAG","adapter.getcount () ="+ Adapter.getcount ());//slide to the bottom of the auto-load, judging the ListView has stopped scrolling and the last visible entry equals the adapter entry //Note here after the ListView is set up Adpter, add a bottom load layout. //So the judging condition is: Lastvisibleindex = = Adapter.getcount () if(Scrollstate = = Scroll_state_idle && Lastvisibleindex = = Adapter.getcount ()) {/** * This is also set to be visible, because when you actually get the data from the network and get the failure. * I'm in the failed method, hiding the bottom loading layout and prompting the user to load the failure. So when you listen again, you need to continue to display the hidden controls. This is not given here because I am simulating the acquisition of data that fails. In practice, simply add a few lines of code. */Pb.setvisibility (view.visible); Tvload.setvisibility (view.visible); Loadmoredata ();//Load more data} }Private void Loadmoredata() { }/** * Monitor the sliding of the ListView */ @Override Public void onscroll(Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) {//Calculate the index of the last visible entryLastvisibleindex = Firstvisibleitem + VisibleItemCount-1;//When all the entries in the adapter are equal to the total number of data to be loaded, remove the view at the bottom if(Totalitemcount = = TotalCount +1) {//Remove load layout at bottomListview.removefooterview (View_more); } }}
The above code is what I said in step 2 and step 2 above. Plus I wrote a note, so I believe everyone looks very simple. The key point is how to tell if the ListView has slipped to the bottom and stopped sliding. I added two lines of log in the code to print the log information. Everyone to debug their own to understand how I judge the key points, but also smart! Hey! We all know, their own people, I will not answer the words.
- The final step is to load more data, that is, to complete the unfinished method in the second stage:
loadMoreData();// 加载更多数据
The specific code is implemented as:
Private void Loadmoredata() {//Gets the total number of entries in this adapter intCount = Adapter.getcount ();//Load 15 data at a time, that is, the execution of the drop-down load if(Count + the< TotalCount) {start = count; End = Start + the; InitData (start, end);//analog network get data operation}Else{//Data less than 15 directly loaded to the endstart = count; end = TotalCount; InitData (start, end);//Analog network acquisition data Cao Zu after all the data has been loaded, remove the view at the bottomListview.removefooterview (View_more); Toast.maketext (mainactivity. This,"The data is all loaded",1). Show (); } }Private void InitData(Final intStartFinal intEnd) {//Analog network request for data, get 15 records at a time NewThread () { Public void Run() {Try{Thread.Sleep (4000);//Simulate time-consuming 3s when acquiring data for(inti = start; I < end; i++) {Lists.add (I,"Data"+ (i +1)); }//Send message to handler update UI, child thread not to update UIMessage message =NewMessage (); Message.what =1; Handler.sendmessage (message); }Catch(Exception e) {E.printstacktrace (); } }; }.start (); }
At this point in the handler also add a case statement, used to refresh the data source, red box marked the place, we add a bit. Finally I will give the project source code, you can download to see my codes:
Okay, here are some pictures of the project:
- Load more data after 15 data,
- Load more data after 30 data,
- Load more data after 45 data,
- After all the data has been loaded, remove the bottom loading layout,
Talk about my sentiment: you need to have your own ideas, others can learn from things, but you need to learn from the point of what. If you don't learn anything, you lose the meaning of sharing! Sharing is to get people to learn more and gain more. I hope this article can give you a little bit of harvest!
Project Source: Click I download project source code
Make a little progress every day! Come on!
The pull-down loading feature of the ListView in Android is implemented