Android custom Controls--the implementation of a pull-down refresh

Source: Internet
Author: User

When we use the ListView , in many cases we need to use the drop-down refresh feature. To understand the underlying implementation of the drop-down refresh, I implemented the effect by customizing the ListView control.

The basic principle of implementation is: Customizing the ListView, giving the listview the load header layout, and then the dynamic control head layout of the reality and hidden. when the ListView is initialized, the header layout is hidden, and when the finger pulls down, the display of the head layout is controlled according to the relationship between the distance the finger moves and the height of the head layout. Detailed control ideas are described in the code behind, the comments in the code are very detailed. Let's take a look:


The implementation code for the header layout is as follows:

<?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=" Horizontal        "> <relativelayout android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:layout_marginleft= "20DP" android:layout_margintop= "5DP" android:padding= "5DP" > <image View android:id= "@+id/iv_arror" android:layout_width= "Wrap_content" android:layout_height = "Wrap_content" android:layout_centerhorizontal= "true" android:padding= "10DP" android:src = "@drawable/refresh_listview_arrow"/> <progressbar android:id= "@+id/pb_list" android:l             Ayout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_centervertical= "true" Android:indeterminatedrawable= "@drawable/custom_progress" android:visibility= "invisible" > </ProgressBar> </rela        tivelayout> <linearlayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_gravity= "Center_horizontal" android:layout_marginleft= "25DP" android:layout_margintop= "12DP" android:orientation= "vertical" android:padding= "5DP" > <textview android:id= " @+id/tv_title "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "a ndroid:layout_gravity= "center" android:layout_margintop= "12DP" android:text= "drop-down Refresh" Androi            D:textcolor= "#FF0000" android:textsize= "20sp"/> <textview android:id= "@+id/tv_time" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_gra           vity= "Center" android:layout_margintop= "3DP" android:text= "2015-03-10 17:07:07" android:textcolor= "@android: Color /darker_gray "android:textsize=" 16sp "/> </LinearLayout></LinearLayout>

Then define a Refreshlistview, inherited from the ListView, overriding its three constructor methods, when the refreshlistview is initialized, Loading a header layout, this header layout is hidden by default.

<span Style= "White-space:pre" ></span>//initial header layout private void Initheaderview () {// Adds a drop-down refresh header layout to the current listview Mheaderview = View.inflate (GetContext (), r.layout.list_refresh_header,null); tvtitle = ( TextView) Mheaderview.findviewbyid (r.id.tv_title); tvtime = (TextView) Mheaderview.findviewbyid (r.id.tv_time);// Drop-down arrow Ivarror = (ImageView) Mheaderview.findviewbyid (r.id.iv_arror);//progress bar PB = (ProgressBar) Mheaderview.findviewbyid ( r.id.pb_list); This.addheaderview (Mheaderview);//Initialize this drop-down refresh of the ListView when the county hides the drop-down refresh of the head layout and then the display of the dynamic control head layout through the code and hide//Hide Header layout First measure a head layout mheaderview.measure (0, 0);//Get the measured height mheaderviewheight = mheaderview.getmeasuredheight ();// Set Paddingtop to negative height, hide header layout mheaderview.setpadding (0,-mheaderviewheight, 0, 0);//Initialize complete layout, initialize two animation effects initanimation ();// Set the current time Tvtime.settext ("Last Refresh Time:" + getcurrenttime ());} 

When the finger touches the screen, the Ontouchevent event is triggered, depending on the finger in the y

<span style= "White-space:pre" ></span>/** * drop-down screen, display the header layout, rewrite the ListView touch screen event */@Overridepublic Boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {case motionevent.action_down:// When the finger is pressed, get the y-coordinate of the current screen starty = (int) ev.getrawy (); break;case motionevent.action_move://the finger moves, get the y-coordinate of the current screen and compare the Y coordinate with the start Starty = =-1) {//ensure starty valid Starty = (int) Ev.getrawy ();} int endY = (int) ev.getrawy ();//The distance from the Y-direction of the screen int dy = endy-starty;//only the screen is down, that is dy>0, and the current ListView shows the first entry, the hidden drop-down refreshed The head layout is slowly and conveniently pointed out if (dy > 0 && this.getfirstvisibleposition () = = 0) {//Allow drop-down refresh box to come out//drop-down refresh box out actually is to layout set padding, First calculate the Paddingint padding = dy-mheaderviewheight;//mheaderview.setpadding (0, padding, 0, 0) according to the distance of the finger movement.//Update the status of the Refresh box// A total of three states, drop-down refresh, refreshing, release refresh//definition of these three states//if the padding is greater than 0 instructions drop-down refresh box has all pulled out, change the status to release the refresh if (padding > 0 && mcurrentstate!) = State_release_refresh) {//Status changed to release refresh, update the status of the drop-down box Mcurrentstate = state_release_refresh;//Update the status of the current drop-down box updatestate ( );} if (padding < 0 && mCurrentState! = State_pull_refresh) {//Status changed to drop-down refresh mcurrentstate = State_pull_refresh;updatestate ();}} Break;case motionevent.action_up://to reset the starty when the finger is lifted up. Change status to refreshing Starty = -1;if (mcurrentstate = = State_release_refresh) {//If you are currently releasing the refresh, the finger is lifted up and the state is changed to Mcurrentstate = State_ The padding of the refreshing;//header layout is set to 0000mheaderview.setpadding (0, 0, 0, 0); Updatestate ();} else {//not fully pulled out, the header layout is hidden mheaderview.setpadding (0,-mheaderviewheight, 0, 0);} break;} return super.ontouchevent (EV);} /** * Update current drop-down box shows the status */private void Updatestate () {//To determine what the current state is, based on the current status update drop-down box to display switch (mcurrentstate) {case State_pull_ refresh://drop-down refresh tvtitle.settext ("drop-down Refresh"), Ivarror.setvisibility (view.visible);p b.setvisibility (view.invisible);// Animate the Arrows Ivarror.startanimation (animdown), break;case state_refreshing://is refreshing tvtitle.settext ("refreshing ..."); Ivarror.clearanimation ();//You must clear the animation before you can hide Ivarror.setvisibility (view.invisible);p b.setvisibility (view.visible);// The method in the calling interface is being refreshed if (mlistener! = null) {//Is refreshing Mlistener.onrefresh ();} Break;case State_release_refresh://Release Refresh Tvtitle.settext ("Release Refresh"), Ivarror.setvisibility (view.visible);p b.setvisibility (view.invisible); Ivarror.startanimation (animup); break;}}

To listen for the action of the pull-down refresh, customize a listener interface to execute the Onrefresh method when it is being refreshed . Provides a way to set up a listener, the listener is implemented by subclasses, and the specific logic that is being refreshed is implemented by subclasses in Onrefresh .

Implementation of the pull-down refresh logic: The listener that sets the dropdown refresh for the current ListView, the essence of the listener is an interface/** * dropdown refreshed Listener *  * @author zhy *  */public interface Onrefreshlistener {//Refresh when executing the method, who implements this interface. Who executes this method public void Onrefresh ();} Onrefreshlistener mlistener;//has a listener, provides a way to set the listener public void Setonrefreshlistener (Onrefreshlistener listener) {// This listneer is from the subclass, is the sub-class definition of the listener Mlistener = listener;}

After the refresh is complete, change the status of the dropdown refresh and hide the drop-down box

<span style= "White-space:pre" ></span>//when the refresh is complete, the drop-down box is hidden/** The data refresh of the calling server, the callback after the completion of the method loaded after the refresh is completed *  @ param issuccess */public void onrefreshcompleted (Boolean issuccess) {//change the state to a drop-down refresh and then hide the drop-down box Mcurrentstate = State_pull_ Refresh;tvtitle.settext ("drop-down Refresh"); Ivarror.setvisibility (view.visible);p b.setvisibility (view.invisible); Mheaderview.setpadding (0,-mheaderviewheight, 0, 0);//Hide//If the refresh is successful, update the last refresh time, or do not update the time if (issuccess) {Tvtime.settext ( "Last Refresh Time:" + getcurrenttime ());}}

After this part of the work is done, a ListView that can implement the pull-down refresh function is defined. It can be used directly in the mainactivity.

SOURCE download


Android custom Controls--the implementation of a 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.