Android Pull-up load more Listview--pulmlistview

Source: Internet
Author: User
Tags addall

Ideas

Today take everyone to achieve a pull-up load more Listview.github Portal: Pulmlistview, welcome everyone fork&&star.

Let's take a look at the idea, if we're going to implement a pull-up load for more ListView, the features we need to implement include:

    1. A custom ListView, and the ListView can determine whether it is currently at the bottom of the page.
    2. A custom footerview that is used to display the UI during the ListView loading process.
    3. Correlate Footerview and ListView, including load time judgment, Footerview display and hide.
    4. Provides a load of more interfaces to facilitate callback users to actually load more feature implementations.
    5. Provides a callback method that loads more ends to add up-to-date data for a user and update related status tags and UI display.

For the above 5 functions, we analyze each of the corresponding implementation methods.

Function 1 (custom listview)

We can implement a custom Pulmlistview by inheriting the ListView.

 Public  class pulmlistview extends ListView {     Public Pulmlistview(Context context) { This(Context,NULL); } Public Pulmlistview(context context, AttributeSet attrs) { This(Context, Attrs,0); } Public Pulmlistview(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);//InitializeInit (); }}

Just implementing the three constructor of the ListView is not enough, we need the ListView to be able to determine whether the current ListView is sliding to the last element.

To determine whether to slide to the last element, we can do this by setting Onscrolllistener for the ListView. The code is as follows:

Private void Init() {Super. Setonscrolllistener (NewOnscrolllistener () {@Override         Public void onscrollstatechanged(Abslistview view,intScrollstate) {//Invoke user-set Onscrolllistener            if(Museronscrolllistener! =NULL) {museronscrolllistener.onscrollstatechanged (view, scrollstate); }        }@Override         Public void onscroll(Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) {//Invoke user-set Onscrolllistener            if(Museronscrolllistener! =NULL{Museronscrolllistener.onscroll (view, Firstvisibleitem, VisibleItemCount, Totalitemcount); }//Firstvisibleitem is the position of the first element that the current screen can display            //VisibleItemCount is the number of elements that the current screen can display            //Totalitemcount is the total number of elements that the ListView contains            intLastvisibleitem = Firstvisibleitem + visibleitemcount;if(!misloading &&!mispagefinished && lastvisibleitem = = totalitemcount) {if(Monpulluploadmorelistener! =NULL) {misloading =true;                Monpulluploadmorelistener.onpulluploadmore (); }            }        }    });}

As you can see from the code comment, you can get the number of elements that the current screen has shown by using (Firstvisibleitem + visibleitemcount), if the number of elements shown is equal to the total number of elements in the ListView, You can now think that the ListView has slipped to the bottom.

Feature 2 (custom Footerview)

Here we can implement a relatively simple footerview, that is, loading more UI layouts. For example, we can show a ProgressBar and a line of text, the code is as follows:

/** * Load more view layouts that can be customized. */ Public  class loadmoreview extends linearlayout {     Public Loadmoreview(Context context) { This(Context,NULL); } Public Loadmoreview(context context, AttributeSet attrs) { This(Context, Attrs,0); } Public Loadmoreview(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);    Init (); }Private void Init() {Layoutinflater.from (GetContext ()). Inflate (R.layout.lv_load_more, This); }}

Layout file:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:id  =" @+id/id_load_more_layout " android:layout_width  =" match_parent " android:layout_height  =" wrap_content " android:orientation  =" horizontal " android:gravity  = "center"  android:layout_margin  =" @dimen/loading_view_margin_layout " ;     <progressbar  android:id< /span>= "@+id/id_loading_progressbar"  android: Layout_width  = "@dimen/loading_view_progress_size"  android:layout_height  =" @dimen/loading_view_progress_size "  android:indeterminate  = "true"  
      
       style 
       = "Android:progressbarstylesmall" />     <TextViewandroid:id="@+id/id_loading_label"android:layout_width= "Wrap_content" android:layout_height="Wrap_content"android:text="@string/page_loading"/ >                                </linearlayout>
Feature 3 (Associated ListView and Footerview)

First, we need to save the Footerview in the ListView with a variable and instantiate it in the constructor.

private View mLoadMoreView;privatevoidinit() {    new LoadMoreView(getContext());}

Second, we need to control the display and concealment of Footerview. Consider the timing of Footerview display and concealment:

    • Time to display: The ListView is at the bottom and there is currently more data to load.
    • Hidden time: The ListView finishes loading more actions.

In order to determine whether there is currently data to be loaded, we need to define a Boolean variable, mispagefinished, to indicate whether the data load is complete.
To ensure that the data is loaded only once during the same time, we also need to define a Boolean variable, misloading, that indicates whether the data is currently in the loading state.

The Footerview shows and hides the time, also has the control state the variable, the code is more easy to implement.

Show Time:

Private void Init() {misloading =false;//initialization is not in the loaded statemispagefinished =false;//Initialize with more data to be loaded by defaultMloadmoreview =NewLoadmoreview (GetContext ());//instantiation of Footerview    Super. Setonscrolllistener (NewOnscrolllistener () {@Override         Public void onscrollstatechanged(Abslistview view,intScrollstate) {//Invoke user-set Onscrolllistener            if(Museronscrolllistener! =NULL) {museronscrolllistener.onscrollstatechanged (view, scrollstate); }        }@Override         Public void onscroll(Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) {//Invoke user-set Onscrolllistener            if(Museronscrolllistener! =NULL{Museronscrolllistener.onscroll (view, Firstvisibleitem, VisibleItemCount, Totalitemcount); }intLastvisibleitem = Firstvisibleitem + visibleitemcount;load more actions when you are in the tail of the ListView and more data needs to be loaded and no loader is currently in progress            if(!misloading &&!mispagefinished && lastvisibleitem = = totalitemcount) {if(Monpulluploadmorelistener! =NULL) {misloading =true;//Load more when the status is set to TrueShowloadmoreview ();//Show load more layoutsMonpulluploadmorelistener.onpulluploadmore ();//Call user settings to load more callback interfaces}            }        }    });}Private void Showloadmoreview() {//here will load more root layout ID set to Id_load_more_layout, easy for users to load more layouts from custom.    if(Findviewbyid (r.id.id_load_more_layout) = =NULL) {Addfooterview (Mloadmoreview); }}

Hidden time:

/** * Load more After the end of the ListView callback method. * * @param ispagefinished page ends * @param newitems page loaded data * @p Aram Isfirstload whether to load data for the first time (used to configure the dropdown refresh frame to avoid page flashes) */ Public void onfinishloading(Booleanispagefinished, List<?> NewItems,BooleanIsfirstload) {misloading =false;//Mark currently does not load more programs in executionSetispagefinished (ispagefinished);//Set pagination to end flag and remove Footerview}Private void setispagefinished(Booleanispagefinished) {mispagefinished = ispagefinished; Removefooterview (Mloadmoreview);}
Function 4 (pull-up load more implementation callback interface)

This is relatively straightforward, and we define a interface that makes it easier for callback users to actually load more implementations.

/** * 上拉加载更多的回调接口 */publicinterface OnPullUpLoadMoreListener {    void onPullUpLoadMore();}private OnPullUpLoadMoreListener mOnPullUpLoadMoreListener;/** * 设置上拉加载更多的回调接口. * @param l 上拉加载更多的回调接口 */publicvoidsetOnPullUpLoadMoreListener(OnPullUpLoadMoreListener l) {    this.mOnPullUpLoadMoreListener = l;}
Feature 5 (Load more end callbacks)

In order to maintain the data collection in Pulmlistview, you must customize a adapter, use the list to store the data collection in adapter, and submit methods for adding and deleting.

Custom adapter:

/** * Abstract adapter. * / Public Abstract  class pulmbaseadapter<T> extends baseadapter {    protectedlist<t> items; Public Pulmbaseadapter() { This. Items =NewArraylist<> (); } Public Pulmbaseadapter(list<t> items) { This. items = items; } Public void Addmoreitems(List<t> NewItems,BooleanIsfirstload) {if(Isfirstload) { This. Items.clear (); } This. Items.addall (NewItems);    Notifydatasetchanged (); } Public void RemoveAllItems() { This. Items.clear ();    Notifydatasetchanged (); }}

Why do you want to add a isfirstload variable in the Addmoreitems method?

This is because the pull-up load is more often used in conjunction with the drop-down refresh . While the drop-down refreshes, it is involved in the ListView data set clear and then AddAll. If there is no isfirstload parameter, The user drop-down refresh to update the ListView data collection must be divided into two steps:

    1. RemoveAllItems and carry out notifydatasetchanged.
    2. Addmoreitems and carry out notifydatasetchanged.

Two consecutive notifydatasetchanged at the same time will cause the screen to splash, so a isfirstload method is presented here. When the data is loaded for the first time, it will clear all the data first, then AddAll, and finally notify.

With a custom adapter, you can write a callback function that loads more ends:

/** * Load more After the end of the ListView callback method. * * @param ispagefinished page ends * @param newitems page loaded data * @p Aram Isfirstload whether to load data for the first time (used to configure the dropdown refresh frame to avoid page flashes) */ Public void onfinishloading(Booleanispagefinished, List<?> NewItems,BooleanIsfirstload) {misloading =false; Setispagefinished (ispagefinished);//Add updated data    if(NewItems! =NULL&& newitems.size () >0{Pulmbaseadapter adapter = (Pulmbaseadapter) ((Headerviewlistadapter) Getadapter ()). Getwrappedadapter ();    Adapter.addmoreitems (NewItems, isfirstload); }}

It is important to note that after adding footerview or headerview, we cannot get our custom adapter through Listview.getadapter, and must follow the steps below:

PulmBaseAdapter adapter = (PulmBaseAdapter) ((HeaderViewListAdapter) getAdapter()).getWrappedAdapter();
Reference
    1. Paginglistview

Android Pull-up load more Listview--pulmlistview

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.