Android custom Control (v) pull-down refresh on Sina Weibo

Source: Internet
Author: User

There are many well-known open-source framework, here to Lala Pulltorefresh This framework, that is, we usually use the drop-down refresh, of course, you ask me what is the use AH? Others have already written, here is mainly learning and practice, the number of practice, and all the natural will.

Say less nonsense, first, then on the code:

1. You must have a drop-down refresh layout to implement the pull-down refresh function, right?

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical "        > <relativelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:paddingbottom= "10dip" android:paddingtop= "10dip" > <linearlayout android:id= "@+i D/layout "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Androi            D:layout_centerinparent= "true" android:gravity= "center" android:orientation= "vertical" > <textview android:id= "@+id/tip" android:layout_width= "Wrap_content" and                roid:layout_height= "Wrap_content" android:text= "@string/state"/> <textview Android:id= "@+id/lastupdate_time"               Android:layout_width= "Wrap_content" android:layout_height= "wrap_content"/> </l inearlayout> <progressbar android:id= "@+id/progress" style= "? Android:attr/progressbarst Ylesmall "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Androi        d:layout_toleftof= "@id/layout" android:layout_marginright= "20dip" android:visibility= "Gone"/> <imageview android:id= "@+id/arrow" android:layout_width= "Wrap_content" Android:la            yout_height= "Wrap_content" android:layout_aligntop= "@+id/layout" android:layout_marginright= "19DP" android:layout_toleftof= "@+id/layout" android:src= "@drawable/arrow_down"/> </relativelayout ></LinearLayout>

2. You have to add it to the layout!
Headview=layoutinflater.from (context). Inflate (r.layout.header_layout, null); This.addheaderview (HeadView);
3. Adding to the layout of the direct display also does not meet the requirements Ah, so this step need to hide the layout, of course, and the previous blog (Android Custom Controls (iv) Imitation NetEase client pull-up load moreAs directly hidden, directly hide meet the requirements, we take here is to set the height of the head layout is a negative value of the actual height, so that the implementation of the hidden function, the moment when the pull, not to show all at once, OK this method can achieve the requirements of the diagram
Headerheight = Headview.getmeasuredheight (); Setheaderviewheight (-headerheight);


/** * Set the height of the head layout *  * @param i */private void setheaderviewheight (int headerheight) {headview.setpadding ( Headview.getpaddingleft (), Headerheight,headview.getpaddingright (), Headview.getpaddingbottom ());// Redraw headview.invalidate ();}

4. After running, White blind, did not realize the desired function, that is, the head layout is not hidden, hey, after the tracking code found that the height of 0, Guo Shen said before measure, Getmeasurewidth () and Getmeasureheight () are zero, okay, Let's measure it first!

private void Measureview (view view) {Viewgroup.layoutparams LP = View.getlayoutparams (); if (LP = = NULL) {LP = new Viewgrou P.layoutparams (viewgroup.layoutparams.match_parent,viewgroup.layoutparams.wrap_content);} int width = viewgroup.getchildmeasurespec (0, 0, lp.width), int height;int tempheight=lp.height;if (tempheight > 0) {Hei Ght = Measurespec.makemeasurespec (tempheight,measurespec.exactly);} else {height = measurespec.makemeasurespec (0, measurespec.unspecified);} View.measure (width, height);}

5. Hidden success, the following to achieve specific functions, drop-down refresh, release refresh, is refreshing these three states, is through gestures to change the state, so here to achieve ontouch, of course, there are onscrolllistener

Need to use Firstvisibleitem to determine if the ListView is sliding up or down, if the firstvisibleitem==0 instructions reach the head of the ListView, of course you also need a Boolean value to determine whether to press the swipe

@Overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) { This.firstvisibleitem=firstvisibleitem;}


Rewrite Ontouchevent, by Firstvisibleitem and Boolean values to determine press, lift, swipe

@Overridepublic boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:if ( Firstvisibleitem = = 0) {Isremark = True;starty = (int) ev.gety ();} Break;case MotionEvent.ACTION_MOVE:onMove (EV); break;case MotionEvent.ACTION_UP:if (state==release) {state=refrash; Reflashviewbystate ();//Update Data Isrefreshlistener.onrefresh ();} else if (state==pull) {state=none;isremark=false;refreshdrawablestate ();} break;} return super.ontouchevent (EV);}

Code is not complete, first explain, followed by all the code

When pressed, if Firstvisibleitem is 0, the description reaches the top of the ListView and can be pressed to assign the Isremark to true, changing the state of the head layout when sliding

/** * Move Process State transform *  * @param ev */private void OnMove (motionevent ev) {if (!isremark) {return;} int tempy = (int) ev.gety (); int space = Tempy-starty;int toppadding = Space-headerheight;switch (state) {case None:if (space>0) {state=pull;reflashviewbystate ();} Break;case pull:setheaderviewheight (toppadding); if (Space>headerheight+30&&scrollstate==scroll_state_ IDLE) {state=release;reflashviewbystate ();} Break;case release:setheaderviewheight (toppadding); if (space

According to the changes of the sliding state and the Y value before the animation, when space is greater than zero, the current state becomes a drop-down refresh, if space is greater than a value, the current state becomes released can be refreshed, when space is greater than 0 is less than a value, the current state is a drop-down refresh state, when space is less than 0 o'clock The current state becomes normal. Of course, when the state changes, the interface changes as well.
/** * Refreshes the current page according to the status */private void Reflashviewbystate () {TextView tip = (TextView) Headview.findviewbyid (r.id.tip); I Mageview arrow = (ImageView) Headview.findviewbyid (R.id.arrow); ProgressBar progress = (ProgressBar) Headview.findviewbyid (r.id.progress); Rotateanimation anim = new Rotateanimation (0, 180,rotateanimation.relative_to_self, 0.5f,rotateanimation.relative_to _self, 0.5f); anim.setduration (+); Anim.setfillafter (true); Rotateanimation anim1 = new Rotateanimation (0,rotateanimation.relative_to_self, 0.5f,rotateanimation.relative_ To_self, 0.5f); anim1.setduration (+); Anim1.setfillafter (true); switch (state) {Case None:setheaderviewheight (- Headerheight); arrow.clearanimation (); break;case PULL:arrow.setVisibility (view.visible);p rogress.setvisibility ( View.gone); Tip.settext ("drop-down Refresh"); Arrow.clearanimation (); arrow.setanimation (ANIM1); Break;case RELEASE: Arrow.setvisibility (view.visible);p rogress.setvisibility (View.gone); Tip.settext ("Release Refresh"); Arrow.clearanimation () ; Arrow.setanimation (anim); break;Case Refrash:setheaderviewheight, Arrow.setvisibility (view.gone);p rogress.setvisibility (View.VISIBLE); Tip.settext ("refreshing"); Arrow.clearanimation (); break;}}

The main changes in the interface are hints, arrows and progress, the normal state, the interface is not visible, the drop-down refresh state, the arrow is visible and down, the hint message for the drop-down refresh and progress not visible, release the refresh state, arrow facing up, progress is not visible, prompting the message for the drop-down refresh , loading status arrows are not visible, progress visible, prompt information changed to being refreshed

Of course, when it becomes loading state, it also loads more data

public interface isrefreshlistener{public void Onrefresh ();} public void Setisrefreshlistener (Isrefreshlistener isrefreshlistener) {This.isrefreshlistener=isrefreshlistener;}

After the data is loaded, also notify the ListView that the refresh ends
/** * get finished data; */public void Reflashcomplete () {state = None;isremark = False;reflashviewbystate (); TextView lastupdatetime = (TextView) Headview.findviewbyid (r.id.lastupdate_time); SimpleDateFormat format = new SimpleDateFormat ("yyyy mm month DD Day HH:MM:SS");D ate date = new Date (System.currenttimemillis ()) ; String time = Format.format (date); Lastupdatetime.settext (time);}

Custom drop-down refresh control It is done, do not know the message, I try to give you answer, customize this thing, write more also know how to write

The following is a full code for the custom drop-down refresh control:

Package Com.sdufe.thea.guo.view;import Java.text.simpledateformat;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.rotateanimation;import Android.widget.abslistview;import Android.widget.ImageView;import Android.widget.progressbar;import Android.widget.textview;import Android.widget.AbsListView.OnScrollListener; Import Android.widget.listview;import Com.sdufe.thea.guo.r;public class Pulltorefreshlistview extends ListView Implements Onscrolllistener {View headview;int headerheight;int firstvisibleitem;int Scrollstate;boolean isRemark;int Starty;int state;final int NONE = 0;final int pull = 1;final int RELEASE = 2;final int refrash = 3;isrefreshlistener IsRef Reshlistener;public Pulltorefreshlistview (Context context, AttributeSet Attrs,int Defstyle) {Super (context, attrs, Defstyle); Initview (context);} PubLic Pulltorefreshlistview (context context, AttributeSet Attrs) {Super (context, attrs); Initview (context);} Public Pulltorefreshlistview (Context context) {super (context); Initview (context);} private void Initview (context context) {Headview = Layoutinflater.from (context). Inflate (R.layout.header_layout,null) ; Measureview (headview); headerheight = Headview.getmeasuredheight (); Setheaderviewheight (-headerHeight); AddView ( Headview); Setonscrolllistener (this);} /** * Calculates the width height * * @param view */private void Measureview (view view) {Viewgroup.layoutparams LP = View.getlayoutparams (); if ( LP = = NULL) {LP = new Viewgroup.layoutparams (viewgroup.layoutparams.match_parent,viewgroup.layoutparams.wrap_content );} int width = viewgroup.getchildmeasurespec (0, 0, lp.width), int height;int tempheight = lp.height;if (Tempheight > 0) {He ight = Measurespec.makemeasurespec (tempheight,measurespec.exactly);} else {height = measurespec.makemeasurespec (0, measurespec.unspecified);} View.measure (width, height);} /** * Set the height of the head layout * * @param i */private void setheaderviewheight (int headerheight) {headview.setpadding (Headview.getpaddingleft (), Headerheight,headview.getpaddingright (), Headview.getpaddingbottom ());//Redraw Headview.invalidate ();} @Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {this.scrollstate = scrollstate;} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) { This.firstvisibleitem = Firstvisibleitem;} @Overridepublic boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:if ( Firstvisibleitem = = 0) {Isremark = True;starty = (int) ev.gety ();} Break;case MotionEvent.ACTION_MOVE:onMove (EV); break;case MotionEvent.ACTION_UP:if (state==release) {state=refrash; Reflashviewbystate ();//Update Data Isrefreshlistener.onrefresh ();} else if (state==pull) {state=none;isremark=false;refreshdrawablestate ();} break;} return super.ontouchevent (EV);} /** * The state transform of the move process * * @param ev */private void OnMove (motionevent EV) {if (!isremark) {return;} int tempy = (int) ev.gety (); int space = Tempy-starty;int toppadding = Space-headerheight;switch (state) {case None:if (space>0) {state=pull;reflashviewbystate ();} Break;case pull:setheaderviewheight (toppadding); if (Space>headerheight+30&&scrollstate==scroll_state_ IDLE) {state=release;reflashviewbystate ();} Break;case release:setheaderviewheight (toppadding); if (spaceHere's how it's used.
<com.sdufe.thea.guo.view.pulltorefreshlistview        android:id= "@+id/pull_to_refresh"        android:layout_ Width= "Match_parent"        android:layout_height= "Wrap_content"/>
The following usage is similar to the ListView, prompting a point to implement the Isrefreshlistener interface, loading more data in the Onrefresh ()

Package Com.sdufe.thea.guo;import Java.util.arraylist;import Java.util.list;import Com.sdufe.thea.guo.view.pulltorefreshlistview;import Com.sdufe.thea.guo.view.pulltorefreshlistview.isrefreshlistener;import Android.os.bundle;import Android.app.activity;import Android.view.menu;import Android.widget.arrayadapter;public class MainActivity extends Activity implements Isrefreshlistener{pulltorefreshlistview ListView; Arrayadapter<string> adapter; list<string> list; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); ListView = (Pulltorefreshlistview) findViewById ( R.id.pull_to_refresh); InitData (); adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1, list); Listview.setadapter (adapter);} private void InitData () {list = new arraylist<string> (); List.add ("123456789"); List.add ("123456789"); List.add (" 123456789 ");} @Overridepublic void Onrefresh () {List.add ("Papa"); List.add ("Mother"); List.add (" I "); Adapter.notifydatasetchanged (); Listview.reflashcomplete ();}}

Today is the end of this, do not understand, leave a message




Android custom Control (v) pull-down refresh on Sina Weibo

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.