Android built (ListView, GridView, etc.) General drop-down refresh, pull-up auto-loaded components

Source: Internet
Author: User

Preface

under Pull Refresh components are used very well in development, and basically networked apps use this approach. For development efficiency, using a recognized open source library is necessarily the most efficient, but the premise of not reinventing the wheel is that you have to know how the wheel was invented and that you can do it yourself. Otherwise just know its principle, and did not go to practice that is also a theory. Do the procedure ape, hands-on will encounter the real problem, otherwise just self-righteous think oneself understand. Today's article is based on their own repeated invention of the wheel of the starting point, through the implementation of the classic, high-usage components to improve their understanding. Let's learn it.

Overall layout structure

The component is the vertical direction of the linearlayout as the root view, respectively, header, Contentview, Foooter, from top to bottom in order, wherein the contentview of the width of the match_parent, The width and height of the footer and header are match_parent, Wrap_content, and the header and Foooter are hidden by setting padding, only the Contentview area is displayed. Triggers a drop-down refresh when the user pulls down to the top and continues to pull down, triggering more actions when the user pulls up to the bottom and continues to pull up.

Although the principle is simple, but the implementation of it will be a lot of small trouble. There is no way to set Ontouchlistener, so using this method will still appear at the top of the ListView "hold" view, not too cool. This implementation method is also quite simple, specifically see Guo Shen blog Android pull-down full parse, teach you how to implement the pull-down refresh function one minute.

Drop-down refresh FundamentalsThe basic principle is that when a user slides a component on the screen,Onintercepttouchevent method to determine whether the Contentview (here we use the ListView as an example to illustrate) the top, if the top and the user continues to decline, then the interception of touch events, that is, in thereturn True in onintercepttouchevent (not quite clear can be referenced as follows: Android Touch Event distribution process . ), so that the touch event is distributed to the Ontouchevent function, and our handling logic for user touch events is primarily in this function.
    /* * to intercept touch events when appropriate, this refers to the appropriate time when Mcontentview slides to the top and is pulled down to intercept touch events, otherwise it is not intercepted and handed to its child * view for processing. * @see * android.view.viewgroup#onintercepttouchevent (android.view.MotionEvent) */@Override public Boolean Onintercepttouchevent (motionevent ev) {/* * This method JUST determines whether we want to intercept the M         Otion.         * If We return true, Ontouchevent'll is called and we do the actual * scrolling there.        */FINAL int action = motioneventcompat.getactionmasked (EV);        Always handle the case of the touch gesture being complete. if (action = = Motionevent.action_cancel | | action = MOTIONEVENT.ACTION_UP) {//Do not intercept touch event,        Let the child handle it return false;                } switch (action) {Case MotionEvent.ACTION_DOWN:mYDown = (int) Ev.getrawy ();            Break Case Motionevent.action_move://int ydistance = (int) Ev.getrawy ()-Mydown;                mydistance = (int) Ev.getrawy ()-Mydown;                Showstatus (Mcurrentstatus); LOG.D (View_log_tag, "%%% isbottom:" + isbottom () + ", Istop:" + istop () + ", Mydistance:" + M                Ydistance);                        If it pulls to the top and is a drop-down, it intercepts the touch event and goes to Ontouchevent to handle the drop-down refresh event if (Istop () && mydistance > 0) || (mydistance > 0 && mcurrentstatus = = status_refreshing))                {return true;        } break;    }//Do not intercept touch event, let the child handle it return false; }
First we record the y-coordinate mydown of the touch point that the user pressed in the Action_down event, and then get the coordinates of the y-axis again in action_move to calculate the difference between the two. If the difference between the sliding is greater than mtouchslop, then continue processing, mtouchslop to determine whether a touch sliding event is valid minimum threshold, if less than this threshold we think this touch sliding event is invalid, such as hand shaking a bit, the distance is very short, so we ignore similar events. within a valid sliding distance, we determine the state of the current component, if it is not in the state being refreshed, then we set different values based on the height of the current ListView paddingtop,paddingtop If the height is greater than 70% of the listview height, then we set the current state to the release can refresh state, which isStatus_release_to_refresh state; instead, we set the status to "continue to pull down" state, i.e. "Status_pull_to_refresh". With this paddingtop height, we will specify that the user pull down the distance to a certain distance before starting the refresh operation, otherwise considered invalid drop. However, regardless of the state at this time, we will modify the header's Padding top property to achieve the effect of stretching the header. when the status is " release can be refreshed", we lift our fingers, we start the Action_up event, at which point we do a drop-down refresh operation. The Ontouchevent code is as follows:
    /* * Handle the Touch event here to achieve a drop-down refresh or a pull-up auto-load problem * @see android.view.view#ontouchevent (android.view.MotionEvent) */@Ov Erride public boolean ontouchevent (Motionevent event) {LOG.D (View_log_tag, "@@@ ontouchevent:action =" + Eve        Nt.getaction ());                Switch (event.getaction ()) {Case MotionEvent.ACTION_DOWN:mYDown = (int) Event.getrawy ();                LOG.D (View_log_tag, "# # Action_down");            Break                Case MOTIONEVENT.ACTION_MOVE:LOG.D (View_log_tag, "# # action_move");                int currenty = (int) Event.getrawy ();                Mydistance = Currenty-mydown; Height greater than header view can refresh if (mydistance >= mtouchslop) {if (Mcurrentstatus! = STAT  us_refreshing) {//if (Mheaderview.getpaddingtop () > Mheaderviewheight *  0.7f) {mcurrentstatus = Status_release_to_refresh;                          Mtipstextview.settext (R.string.pull_to_refresh_release_label);                            } else {mcurrentstatus = Status_pull_to_refresh;                        Mtipstextview.settext (R.string.pull_to_refresh_pull_label);                    }} rotateheaderarrow (); int scaleheight = (int) (mydistance * 0.8f),//go to the sliding distance of 80%, reduce the sensitivity of the//y-axis sliding distance is less than one of the screen height of 4 points when the header will be stretched, the contrary remains                    Change if (ScaleHeight <= mscrheight/4) {adjustheaderpadding (scaleheight);            }} break;                Case MOTIONEVENT.ACTION_UP://drop-down Refresh specific operation Dorefresh ();            Break        Default:break;    } return true; }
When lifting your finger, start the refresh operation, the code is as follows:
    /** * Perform a refresh operation */private final void Dorefresh () {if (Mcurrentstatus = = Status_release_to_refresh) {            Set the status to be refreshed mcurrentstatus = status_refreshing;            Marrowimageview.clearanimation ();            Hides the arrow icon in the header marrowimageview.setvisibility (View.gone);            Set the progress bar in the header to be visible mheaderprogressbar.setvisibility (view.visible);            Set some text mtimetextview.settext (R.string.pull_to_refresh_update_time_label);            SimpleDateFormat SDF = new SimpleDateFormat ();            Mtimetextview.append (Sdf.format (New Date ()));            Mtipstextview.settext (R.string.pull_to_refresh_refreshing_label);            Executes the callback if (Mpullrefreshlistener! = null) {Mpullrefreshlistener.onrefresh ();        }//causes the Headview to display normally until Refreshcomplete is called and then hides the new Headerviewhidetask (). Execute (0);          } else {//Hide header View  Adjustheaderpadding (-mheaderviewheight); }    }
In the refresh state, the header is displayed normally, that is, the padding top needs to be set to 0, we use an asynchronous task to gradually modify the value of the padding top, so that the header from the stretch effect gradually, smooth restore the original size. After the user invokes the Refreshcomplete () function, after the refresh is complete, the padding top of the ListView is gradually resized to hide it. At this point, the entire drop-down refresh process is complete.swipe to the bottom to automatically load sliding to the bottom of the auto-load is relatively much simpler, and we are also using the Contentview as a ListView case to illustrate. The principle is to listen for the scroll events of the ListView (that is, Contentview) , so if the type of Contentview does not support scrolling events, this function cannot be implemented. The ListView meets the requirements, so it can be loaded automatically. In the Onscroll function, we determine if the ListView is the last item, and if it is to the last item, it shows footer and starts loading. Represents the end of the load when the user calls the Loadmorecomplete function. Hide footer At this time, the whole process is over.
/* * Scrolling event, implementation sliding to the bottom pull up load more * @see ANDROID.WIDGET.ABSLISTVIEW.ONSCROLLLISTENER#ONSC     Roll (android.widget. * Abslistview, int, int, int) */@Override public void onscroll (Abslistview view, int firstvisibleitem, int Visi        Bleitemcount, int totalitemcount) {log.d (View_log_tag, "&&& mydistance =" + mydistance); if (Mfooterview = = NULL | | mydistance >= 0 | | mcurrentstatus = status_loading | | mcurrentstatus        = = status_refreshing) {return;    } loadmore (); /** * Pull down to the bottom when loading more */private void Loadmore () {if (Isshowfooterview () && Mloadmorelistener!            = null) {Mfootertextview.settext (R.string.pull_to_refresh_refreshing_label);            Mfooterprogressbar.setvisibility (view.visible);            Adjustfooterpadding (0);            Mcurrentstatus = status_loading;        Mloadmorelistener.onloadmore (); }    }
Where the Isshowfooterview function called in the Loadmore function is used to determine if it is at the bottom, the code is as follows:
     /* * Drop to the last item in the ListView to return True, will start automatically load     * @see Com.uit.pullrefresh.base.pullrefreshbase#isshowfooterview ()     */    @Override    protected Boolean Isshowfooterview () {        if (Mcontentview = = NULL | | Mcontentview.getadapter () = = null) {            return false;        }        return mcontentview.getlastvisibleposition () = = Mcontentview.getadapter (). GetCount ()-1;    }
OK, at this point the entire core process is complete.

Listview



TextView drop-down refresh


GitHub Address

Punch here!

Android-built (ListView, gridview, etc.) common drop-down refresh, pull-up auto-loaded components

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.