Listview pull-down refresh

Source: Internet
Author: User

After reading a lot of listview pull-down refresh results, I am not satisfied. At present, there are two common practices: one is to rewrite foreigners, one is to inherit the listview method, the code is very difficult to read, and it is hard to implement the effect, in terms of the effect, it will be pulled down accidentally. the user experience is very bad, and it cannot be the effect of "Sina Weibo" or "QQ space. The other one is written by ourselves and completed by combining controls. The effect is acceptable, but the native listview is lost because it inherits layout, as a control encapsulation, the maintenance volume is too large.

By referring to these two methods, I wrote a listview, which should be the effect of "Sina Weibo" and "QQ space. It is relatively secure and refresh will not be motionless. You can drag up and down with confidence, and the logic is also relatively brief. I don't have much to say about the code!

 

The XML layout of the header item. Note that this layout must be linearlayout. The layout will be automatically typeset when being dragged with the relative layout, and the effect will be lost.

<? 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 = "wrap_content"> <relativelayout Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: layout_marginbottom = "5dp" Android: layout_margintop = "5dp"> <textview Android: Id = "@ + ID/textview1" Android: layout_width = "wrap_content" Android: layout_height =" Wrap_content "Android: layout_centerhorizontal =" true "Android: text =" pull-down refresh "Android: textcolor =" #000000 "Android: textsize =" 14sp "/> <textview Android: id = "@ + ID/textview2" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_below = "@ + ID/textview1" Android: layout_centerhorizontal = "true" Android: text = "Last Update Time: not updated" Android: textsize = "12sp"/> <imageview Android: Id = "@ + ID/IM Ageview1 "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_centervertical =" true "Android: layout_marginleft =" 70dp "Android: src = "@ drawable/refresh_down"/> <progressbar Android: Id = "@ + ID/progressbar1" style = "? Android: ATTR/progressbarstylesmall "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_centervertical =" true "Android: layout_marginleft = "70dp"/> </relativelayout> </linearlayout>

 

Code:

Package synway. mhcs. controls. pulllist; import Java. text. simpledateformat; import Java. util. calendar; import synway. mhcs. r; 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. widget. abslistview; import android. widget. imageview; import android. widget. linearlayo Ut; import android. widget. listview; import android. widget. progressbar; import android. widget. textview;/*** in order to give you something ready for use, I have killed a lot of brain cells and wrote it. For more information, enter the original address !! **/Public class pulldownlist extends listview implementsandroid. widget. abslistview. onscrolllistener {public pulldownlist (context) {super (context); Init ();} public pulldownlist (context, attributeset attrs) {super (context, attrs ); init ();} public pulldownlist (context, attributeset attrs, int defstyle) {super (context, attrs, defstyle); Init ();} /** ============================ control set at the top of the list ====== =============== */Private progressbar progressbar_top = NULL; private imageview imageview_top = NULL; private textview txttime_top, txtrefresh_top; /** view at the top of the list */private linearlayout topviewitem = NULL;/** view height at the top of the list */private int topviewitemheight = 0; /** =================================================== ======================= * // ** =======================================list set of controls at the bottom =============================== */private linearlayout bottomviewitem = nu Ll; private progressbar progressbar_bottom = NULL; private textview txtbottom = NULL; /** =================================================== ======================= * // ** ====================================== four variables for logical judgment =================================* // ** whether the first line is on the screen */private Boolean isfirstitemshow = false; // The first line loads the row. If you scroll the list to the top, no matter whether the row is compressed or opened, it will be deemed that the screen is displayed/** whether there is a loading intention, that is, the intention to load the first line */private Boolean iswanttoextrude = true; /** whether the image has been opened */private Boolean isext Ruded = false;/** whether or not loading */private Boolean isloading = false; /** =================================================== =====================* // ** time format */private simpledateformat SDF = new simpledateformat ("HH: MM: SS ");/** initialize */private void Init () {setonscrolllistener (this); layoutinflater = (layoutinflater) getcontext (). getsystemservice (context. layout_inflater_service); // initialize the tool bar bottomviewitem at the bottom of the list = (L Inearlayout) layoutinflater. inflate (R. layout. base_list_item_bottom, this, false); progressbar_bottom = (progressbar) bottomviewitem. findviewbyid (R. id. progressbar1); txtbottom = (textview) bottomviewitem. findviewbyid (R. id. textview1); // initialize topviewitem = (linearlayout) layoutinflater at the top of the list. inflate (R. layout. base_list_item_top, this, false); topviewitem. setonclicklistener (null); // make it not an item in the list to click pro Gressbar_top = (progressbar) topviewitem. findviewbyid (R. id. progressbar1); progressbar_top.setvisibility (view. invisible); imageview_top = (imageview) topviewitem. findviewbyid (R. id. imageview1); txttime_top = (textview) topviewitem. findviewbyid (R. id. textview2); txtrefresh_top = (textview) topviewitem. findviewbyid (R. id. textview1);/** 3 to hide the topviewitem: 1. measure the length and width after the screen is added. Because it is not added to the screen, it is invalid to directly obtain the length and width. obtained height * 3. set The top margin is set to a negative height, which is equivalent to converting the height to 0 to achieve the hidden effect (by the way, even if the topviewitem sets its height to 0 through padding *, in the list, it will still occupy the pixels of a row, and the list still considers it to be 0th rows) * // the first step of measureview (topviewitem); // the second step of topviewitemheight = topviewitem. getmeasuredheight (); // step 3 topviewitem. setpadding (topviewitem. getpaddingleft (),-1 * topviewitemheight, topviewitem. getpaddingright (), topviewitem. getpaddingbottom (); // Add it to the list addheaderview (topviewitem);}/** when the list stops rolling in any form (automatically rolling or dragging by hand), as shown in If the first line already appears, it is deemed that there is an intention to load. If the first line does not appear, it is deemed that there is no intention to load */@ overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {If (isloading) // No processing is performed when loading. {return;} // when the list is in any form (Automatic rolling or dragging/dragging) if (scrollstate = scroll_state_idle) {If (isfirstitemshow) {iswanttoextrude = true; // system. out. println ("the intent is set to true by onscrollstatechanged");} else {iswanttoextrude = false; // system. out. println ("intention to be onscrollstat Set echanged to false ") ;}}/ ** to check whether 0th rows appear on the screen based on whether the top row of the screen is 0th rows during list scrolling, whether the loading intention exists */@ overridepublic void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {If (isloading) // if it is already loaded, no processing is performed. {return;} If (firstvisibleitem = 0) {isfirstitemshow = true; // system. out. println ("isfirstitemshow is set to true by onscroll");} else {isfirstitemshow = false; iswanttoextrude = false; // system. Out. println ("intention to be set to false by onscroll");}/** Y axis coordinate of the last finger touch screen */private float lastactiondown_y = 0; @ overridepublic Boolean ontouchevent (motionevent eV) {boolean result = super. ontouchevent (EV); If (isloading) // if it is already loaded, no processing is performed. {return result;} switch (ev. getaction () {// obtain the position of the Y axis when the finger is pressed. It is used to calculate the distance between the finger and the case motionevent when dragging. action_down: lastactiondown_y = eV. gety (); break;/** 1. if there is an intention to load, the first line is stretched. However, the loading intention is only to say that he may need to pull it. If he has the loading intention, he still needs to slide his fingers down to load it. * When the finger slides up, the user does not want to open it. The value of the sliding Y axis is negative (close to 0 at the beginning, and the absolute value is gradually increased at the end ). however, the loading intention may not be immediately reset to false by onscroll at that moment. At that moment, the paddingtop of the stretch bar may be set to a negative value very close to 0, * obviously, the stretch bar is displayed. therefore, this action must be performed only when the value is greater than 0. 2. if there is no intention of loading, there are two possibilities. One is a normal touch without any processing. * The other is that it was opened at the time, and the user did not want to pull it again, so he pushed it back again (you should have a deep understanding ). After pushing back, the loading intent is converted to false by the onscroll function. * In this case, the first line should be recompressed to its original state. */Case motionevent. action_move: // float gapvalue_y = eV. gety ()-lastactiondown_y; If (iswanttoextrude) {If (gapvalue_y> 0) {// execute the task after more than 5 pixels. This is to improve the user experience and shake the image without a touch, it has nothing to do with its own logic isextruded = true; // The New paddingtop should be the sliding distance minus the total height, so that the loading row will have a slow pull effect int newpaddingtop = (INT) gapvalue_y-topviewitemheight; topviewitem. setpadding (0, newpaddingtop, 0, 0); // if the new paddingtop is greater than or equal to 0, it indicates that it has been fully opened. If (newpaddingtop> = 0) {Setcontrol (2) ;}else {setcontrol (1) ;}} else {// system. out. println ("less than 0, push up, do nothing, wait for the intention to be reset");} else {If (isextruded) {// push back isextruded = false; topviewitem. setpadding (0,-1 * topviewitemheight, 0, 0); // system. out. println ("reset") ;}} break; // when you pick up your finger, you do not need to do anything normally. // When you pick up your finger, if it has been fully opened, load the case motionevent. action_up: If (isextruded) {// system. out. println ("paddingtop:" + // topviewitem. getpaddingtop (); // system. out. println ("topviewitemheight:" + topviewitemheight); If (topviewitem. getpaddingtop ()> = 0) {If (this. onpdlistener! = NULL) {isloading = true; topviewitem. setpadding (0, 0, 0, 0); setcontrol (3); this. onpdlistener. onrefresh ();} else {topviewitem. setpadding (0,-1 * topviewitemheight, 0, 0); isextruded = false; setselection (0); // return to the first line} else {topviewitem. setpadding (0,-1 * topviewitemheight, 0, 0); isextruded = false; setselection (0); // return the first line} break; default: break;} return result ;} // improves performance and prevents meaningless duplicate values of private int controlstat E =-1;/*** set the display content of the control ** @ Param state * 0 indicates that the control is reset by the user; 1 indicates that the control is refreshed by the drop-down; 2 indicates that the control is released and refreshed, 3 indicates refreshing */private void setcontrol (INT state) {If (controlState! = State) {controlState = State; If (State = 0) {imageview_top.setvisibility (view. visible); progressbar_top.setvisibility (view. invisible);} else if (State = 1) {txtrefresh_top.settext ("pull-down Update"); imageview_top.setimageresource (R. drawable. refresh_down);} else if (State = 2) {txtrefresh_top.settext ("Release update now"); imageview_top.setimageresource (R. drawable. refresh_up);} else if (State = 3) {imageview_top.setvi Sibility (view. invisibility); progressbar_top.setvisibility (view. visible); txtrefresh_top.settext ("Updating... ");}}} /* = =============== * // ** set the refresh listener */Public void setonpdlisten (onpdlistlistener onpdlistener) {This. onpdlistener = onpdlistlistener;}/** remove refresh listener */Public void removepdlisten () {This. onpdlistener = NULL ;} /* ===================================================== === ============= * // * ============================ Load more public functions =========== */private Boolean isloadingmoreviewenabled = true; /** initialize and load more toolbar and add it to the bottom of the list */Public void loadingmoreview_init () {// initialize the addfooterview (bottomviewitem) control at the bottom of the list; bottomviewitem. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {If (onpdlistlistener! = NULL & isloadingmoreviewenabled) {progressbar_bottom.setvisibility (view. visible); txtbottom. settext ("loading... "); onpdlistener. onloadmore () ;}});}/** complete loading more */Public void loadingmore_finish () {progressbar_bottom.setvisibility (view. invisible); txtbottom. settext ("click to load more");}/** set whether to enable */Public void loadingmore_enabled (Boolean enabled) {progressbar_bottom.setvisibility (view. invisible); isloadingmorevi Ewenabled = enabled; If (Enabled) {txtbottom. settext ("click to load more");} else {txtbottom. settext ("the last line has been reached ");}} /* ===================================================== =================== * // * ========================================== refresh Part public Functions ===================================* // ** pop up a refresh entry and trigger the onrefresh interface */Public void startrefresh () {If (! Isloading & this. onpdlistener! = NULL) {isloading = true; topviewitem. setpadding (0, 0, 0, 0); setcontrol (3); setselection (0); // select the first line this. onpdlistener. onrefresh () ;}}/*** end refresh *** @ Param isupdatetime * Indicates whether to update the time. If the refresh fails, you can choose not to update */Public void stoprefresh (Boolean isupdatetime) {// restore all variables, reset the initial values in the first line, and select if (isloading) in the first line {// reset all variables isfirstitemshow = false; iswanttoextrude = true; isextruded = false; isloading = false; // reset the content of the drop-down control setcontrol (0); // Update time if (isupdatetime) {txttime_top.settext ("Last Update time:" + SDF. format (calendar. getinstance (). gettime ();} topviewitem. setpadding (0,-1 * topviewitemheight, 0, 0); setselection (0 );}} /* ===================================================== =================* // ** indicates the length and width of a view measurement because before the view is added to the interface, it is invalid to directly retrieve the length and width. the length and width of the control cannot be obtained when the oncreat of the activity */Private Static void measureview (view child) {viewgroup. layoutparams P = child. getlayoutparams (); If (P = NULL) {P = new viewgroup. layoutparams (viewgroup. layoutparams. fill_parent, viewgroup. layoutparams. wrap_content);} int childwidthspec = viewgroup. getchildmeasurespec (0, 0 + 0, P. width); int lpheight = P. height; int childheightspec; If (lpheight> 0) {childheightspec = measurespec. makemeasurespec (lpheight, measurespec. exactly);} else {childheightspec = measurespec. makemeasurespec (0, measurespec. unspecified);} child. measure (childwidthspec, childheightspec);} private onpdlistener = NULL; public interface onpdlistlistener {public void onrefresh (); Public void onloadmore ();}}

 

 

 

You can find the icons up and down. Old man is too lazy to find them for you ~!

 

Demo in my resources ~~ Get it by yourself. You need to score it.

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.