ListView Pull-up resistor pull-down refresh

Source: Internet
Author: User
Tags gety


The main use of this several documents. Mainactivity is the interface of the Activity,myadapter is the listview of its own definition adaptation, Mylistview is its own definition of the head of the Liistview, assuming that only need to pull the load on the need; activity_ Main.xml is a live interface. Item.xml is a sub-layout of the ListView with just one textview,listview_footer.xml that is a ListView loaded with many other bottom layouts, listview_ Header.xml is the head layout of the ListView.


Mainactivity.java

Package Com.example.listview;import Java.util.arraylist;import Java.util.list;import Android.annotation.suppresslint;import Android.app.activity;import Android.os.asynctask;import Android.os.Bundle; Import Android.os.handler;import Android.view.layoutinflater;import Android.view.view;import Android.widget.abslistview;import Android.widget.abslistview.onscrolllistener;import Android.widget.Toast;import Com.example.listview.mylistview.onrefreshlistener;public class Mainactivity extends Activity implements onscrolllistener{/** listview*/private Mylistview listview;/** own defined adapter*/private MyAdapter adapter;/** altogether data */ Private list<string> list=new arraylist<string> ();/** ListView Bottom Layout */private View footer;private Handler Handler private int count=0; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);/** configuration Good listview*/listview= (Mylistview) Findviewbyid (R.id.listView);/** Add bottom layout, before setadapter, otherwise not effectiveFruit */footer=layoutinflater.from (this). Inflate (r.layout.listview_footer, null); Listview.addfooterview (footer);/** Fit Listview*/adapter=new Myadapter (this, list); Listview.setadapter (adapter);/** add a thread to set the time to have the wait effect */handler=new         Handler (); Listview.setonscrolllistener (this); Listview.setonrefreshlistener (new Onrefreshlistener () {@Override public void Onrefresh () {new asynctask<void, void, void> () {protected Vo                        ID doinbackground (Void ... params) {try {thread.sleep (1000);                        } catch (Exception e) {e.printstacktrace ();                        }//List.add ("content added after Refresh");                    return null; } @Override protected void onpostexecute (void result) {adapt                        Er.notifydatasetchanged (); Listview.onrefreshcomplete ();                   }}.execute (null, NULL, NULL); }       });  SetData (); }/** * Bottom Scrolling monitor */@Overridepublic void onscrollstatechanged (final abslistview view, int scrollstate) {/** When scrolling stops at the bottom of the same time *  /if (scrollstate = = Onscrolllistener.scroll_state_idle && (view.getlastvisibleposition () = = View.getcount ()- 1) {/** in order to have data load waiting time.                    Assuming a network data request, there is no need to request the interface directly here ok*/handler.postdelayed (new Runnable () {@Override                    public void Run () {setData ();                    /** let the refreshed data from the screen start to display, assuming that the location is not set, the ListView data update will run to the first Data start display */Listview.setselection (View.getcount ()-1);                     }}, 2000); }} @Overridepublic void Onscroll (Abslistview arg0, int arg1, int arg2, int arg3) {}/** Put the data, assuming that your data can be paged to get it is not required, here is to have pagination Data */@SuppressLint ("Showtoast") private void SetData () {//Remove the bottom layout if (count>50) {Listview.removefootervi When the data reaches the total amount)EW (footer); Toast.maketext (This, "There's not a lot of other data,"). Show (); return;} for (int i=count;i<count+10;i++) {list.add ("data" +i);} count=count+10;/** Notification Adapter Data Change */adapter.notifydatasetchanged ();}}

Mylistview.java


Package Com.example.listview;import Java.util.date;import Android.content.context;import Android.util.AttributeSet ; Import Android.view.layoutinflater;import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup;import Android.view.animation.linearinterpolator;import Android.view.animation.rotateanimation;import Android.widget.abslistview;import Android.widget.abslistview.onscrolllistener;import Android.widget.imageview;import android.widget.LinearLayout; Import Android.widget.listview;import android.widget.progressbar;import android.widget.textview;/** *     ListView joins Refresh header itself defined ListView * * @author Liu Zi not * * */public class Mylistview extends ListView implements Onscrolllistener { Private final static int release_to_refresh = 0;//The state value of the drop-down procedure private final static int pull_to_refresh = 1;    Return from drop-down to non-refreshed status value private final static int refreshing = 2;//State value being refreshed private final static int done = 3;    Private final static int LOADING = 4; The distance from the actual padding is offset from the interface.Proportional private final static int RATIO = 3;    Private Layoutinflater Inflater;    ListView Header drop-down refresh layout private LinearLayout Headerview;    Private TextView Lvheadertipstv;    Private TextView Lvheaderlastupdatedtv;    Private ImageView lvheaderarrowiv;    Private ProgressBar Lvheaderprogressbar;    Defines the height of the drop-down refresh layout of the head private int headercontentheight;    Private rotateanimation animation;    Private Rotateanimation reverseanimation;    private int starty;    private int state;    Private Boolean isback;    Used to ensure that the value of Starty is only recorded once in a full touch event by the private Boolean isrecored;    Private Onrefreshlistener Refreshlistener;    Private Boolean isrefreshable;        Public Mylistview (Context context) {super (context);    Init (context);        } public Mylistview (context context, AttributeSet Attrs) {Super (context, attrs);    Init (context); } private void Init (context context) {Setcachecolorhint (Context.getresources (). GetColor (Android).     R.color.transparent));   Inflater = Layoutinflater.from (context);        Headerview = (linearlayout) inflater.inflate (r.layout.listview_header, NULL);        Lvheadertipstv = (TextView) headerview. Findviewbyid (R.ID.LVHEADERTIPSTV);        LVHEADERLASTUPDATEDTV = (TextView) headerview. Findviewbyid (R.ID.LVHEADERLASTUPDATEDTV);        LVHEADERARROWIV = (ImageView) headerview. Findviewbyid (R.ID.LVHEADERARROWIV);        Sets the minimum height and width of the drop-down refresh icon Lvheaderarrowiv.setminimumwidth (70);        Lvheaderarrowiv.setminimumheight (50);        Lvheaderprogressbar = (ProgressBar) headerview. Findviewbyid (R.id.lvheaderprogressbar);        Measureview (Headerview);        Headercontentheight = Headerview.getmeasuredheight ();        Set the padding, just the height of a negative entire layout at the top, just to hide the head headerview.setpadding (0,-1 * headercontentheight, 0, 0);        Redraw the headerview.invalidate ();        Add the dropdown refresh layout to the top of the ListView Addheaderview (Headerview, NULL, FALSE); //Set the scrolling listener event Setonscrolllistener (this);                Set Rotation Animation Event animation = new Rotateanimation (0, -180, rotateanimation.relative_to_self, 0.5f,        Rotateanimation.relative_to_self, 0.5f);        Animation.setinterpolator (New Linearinterpolator ());        Animation.setduration (250);        Animation.setfillafter (TRUE); Reverseanimation = new Rotateanimation ( -180, 0, Rotateanimation.relative_to_self, 0.5f, Rota        Teanimation.relative_to_self, 0.5f);        Reverseanimation.setinterpolator (New Linearinterpolator ());        Reverseanimation.setduration (200);        Reverseanimation.setfillafter (TRUE); The starting state is the state of the drop-down refresh.        So state = done for done;    Whether isrefreshable = False is being refreshed; } @Override public void onscrollstatechanged (Abslistview view, int. scrollstate) {} @Override public void O Nscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {} @Override public boolean ontouchevent (motionevent ev) {if (isrefreshable) {switch (ev.ge Taction ()) {case MotionEvent.ACTION_DOWN:if (!isrecored) {isrecored = True                    ;            Starty = (int) ev.gety ();//Record the current position when the finger is pressed} break; Case MotionEvent.ACTION_UP:if (state! = Refreshing && state! = LOADING) {if (s                        Tate = = Pull_to_refresh) {state = done;                    Changeheaderviewbystate ();                        } if (state = = Release_to_refresh) {state = refreshing;                        Changeheaderviewbystate ();                    Onlvrefresh ();                }} isrecored = false;                Isback = false;            Break Case MotionEvent.ACTION_MOVE:int tempy = (int) ev.gEty ();                    if (!isrecored) {isrecored = true;                Starty = Tempy; } if (state! = refreshing && isrecored && state! = LOADING) {//guaranteed in setting PA In the process of dding, the current position is always at head. Otherwise assume that when the list goes out of the screen, when it is pushed up. The list will scroll at the same time//be able to let go and refresh if (state = = Release_to_refresh) {SE                        Tselection (0); Pushed up. Pushed to the screen enough to cover up the head, but it hasn't been pushed to the point of all the cover-up if (((tempy-starty)/RATIO < Headercontentheight)//change by Release refresh State To drop-down refresh status && (Tempy-starty) > 0) {state = Pull_to_re                            FRESH;                        Changeheaderviewbystate ();                            }//push to the top all at once else if (tempy-starty <= 0) {//changed from release refresh state to done state                            state = done;  Changeheaderviewbystate ();                      }}//has not reached the display when the refresh is released, done or Pull_to_refresh state                        if (state = = Pull_to_refresh) {setselection (0); Pull down to the state that can enter Release_to_refresh if ((tempy-starty)/RATIO >= headercontentheight) {//by done or                            The drop-down refresh state transitions to loosen the flush states = Release_to_refresh;                            Isback = true;                        Changeheaderviewbystate ();                            }//pushed to the top of else if (tempy-starty <= 0) {//by done or drop-down refresh state to the done state                            state = done;                        Changeheaderviewbystate (); }}//Done status if (state = = done) {if (Te                            Mpy-starty > 0) {state = Pull_to_refresh; ChangeheadErviewbystate ();                        }}//update Headview's size if (state = = Pull_to_refresh) { Headerview.setpadding (0,-1 * headercontentheight + (tempy-starty)/RATIO,                    0, 0);                        }//Update Headview paddingtop if (state = = Release_to_refresh) {                    Headerview.setpadding (0, (tempy-starty)/ratio-headercontentheight, 0, 0);            }} break;            Default:break;    }} return super.ontouchevent (EV); }//When the state changes. Call the method. To update the interface private void Changeheaderviewbystate () {switch (state) {case Release_to_refresh:lvhea            Derarrowiv.setvisibility (view.visible);            Lvheaderprogressbar.setvisibility (View.gone); Lvheadertipstv.setvisibility (View.visibLE);            Lvheaderlastupdatedtv.setvisibility (view.visible); Lvheaderarrowiv.clearanimation ();//Clear Animation lvheaderarrowiv.startanimation (animation);//Start animation effect Lvheade            Rtipstv.settext ("release Refresh");        Break            Case PULL_To_REFRESH:lvHeaderProgressBar.setVisibility (View.gone);            Lvheadertipstv.setvisibility (view.visible);            Lvheaderlastupdatedtv.setvisibility (view.visible);            Lvheaderarrowiv.clearanimation ();            Lvheaderarrowiv.setvisibility (view.visible);                is the IF (isback) {Isback = False, which is transformed by the Release_to_refresh State;                Lvheaderarrowiv.clearanimation ();                Lvheaderarrowiv.startanimation (reverseanimation);            Lvheadertipstv.settext ("drop-down refresh");            } else {Lvheadertipstv.settext ("drop-down refresh");        } break;            Case REFRESHING:headerView.setPadding (0, 0, 0, 0); LvheaderprogressBar.setvisibility (view.visible);            Lvheaderarrowiv.clearanimation ();            Lvheaderarrowiv.setvisibility (View.gone);            Lvheadertipstv.settext ("refreshing ...");            Lvheaderlastupdatedtv.setvisibility (view.visible);        Break            Case DONE:headerView.setPadding (0,-1 * headercontentheight, 0, 0);            Lvheaderprogressbar.setvisibility (View.gone);            Lvheaderarrowiv.clearanimation ();            Lvheaderarrowiv.setimageresource (R.drawable.head_arrow);            Lvheadertipstv.settext ("drop-down refresh");            Lvheaderlastupdatedtv.setvisibility (view.visible);        Break }}//This method is copied directly from a dropdown refresh on the network demo, here is "expected" headview width and height private void Measureview (View child) {VIEWGR Oup.        Layoutparams params = Child.getlayoutparams (); if (params = = null) {params = new Viewgroup.layoutparams (ViewGroup.LayoutParams.MATCH_PARE NT, ViewGroup.LayoutParams.WRAP_CONTENT);        } int childwidthspec = viewgroup.getchildmeasurespec (0, 0 + 0, params.width);        int lpheight = Params.height;        int childheightspec; if (Lpheight > 0) {childheightspec = Measurespec.makemeasurespec (Lpheight, MEASURESPEC.E        xactly);        } else {childheightspec = Measurespec.makemeasurespec (0, measurespec.unspecified);    } child.measure (Childwidthspec, Childheightspec);        } public void Setonrefreshlistener (Onrefreshlistener refreshlistener) {this.refreshlistener = Refreshlistener;    Isrefreshable = true;    } public interface Onrefreshlistener {public void Onrefresh ();        } @SuppressWarnings ("deprecation") public void Onrefreshcomplete () {state = done;        Lvheaderlastupdatedtv.settext ("Recent update:" + new Date (). toLocaleString ());    Changeheaderviewbystate (); } private void Onlvrefresh () {if (RefreshlistenEr! = null) {Refreshlistener.onrefresh (); }    }}

Listview_footer.xml

<?

XML version= "1.0" encoding= "Utf-8"?

><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Fill_ Parent " android:layout_height=" wrap_content " android:gravity=" center " android:layout_margintop=" 10DP " android:orientation=" Horizontal "> <progressbar android:id=" @+id/footer_progress " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" /></linearlayout>


Listview_header.xml



<?xml version= "1.0" encoding= "Utf-8"?><!--the head of the ListView--><linearlayout xmlns:android= "/http/     Schemas.android.com/apk/res/android "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "> <!--Content-<relativelayout android:id= "@+id/head_contentlayout" android:layout_width= "Fill_ Parent "android:layout_height=" wrap_content "android:background=" @drawable/list_header_bg "Android:pa            ddingleft= "30DP" > <!--arrow image, progress Bar--<framelayout android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout _centervertical= "true" > <!--arrow--<imageview android:id= "@+id/lvheader                Arrowiv "android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:layout_gravity= "Center"               android:src= "@drawable/head_arrow"/> <!--progress Bar--<progressbar Android:id= "@+id/lvheaderprogressbar" style= "? Android:attr/progressbarstylesmall" Android Oid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_gravity= "Center" android:visibility= "Gone"/> </FrameLayout> <!--tips, recent update--& Lt LinearLayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" and Roid:layout_centerhorizontal= "true" android:gravity= "Center_horizontal" android:orientation= "Vertica                L "> <!--Tips-<textview android:id=" @+id/lvheadertipstv " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "drop-down brush New "andRoid:textsize= "13sp"/> <!--recent update-<textview android:id= "@+id/lvheader                Lastupdatedtv "android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:text= "Latest update" android:textsize= "10sp"/> </LinearLayout> </relativel Ayout></linearlayout>

Download link


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

ListView Pull-up resistor pull-down refresh

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.