Android Learning (45)--custom Control (9) drop-down Refresh (add footer)

Source: Internet
Author: User

Style effects



1, create the bottom of the layout layout_footer.xml

<?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 "android:gravity=" center "and roid:orientation= "Horizontal" > <progressbar android:layout_width= "wrap_content" Android:layout_hei ght= "Wrap_content" android:layout_marginbottom= "10DP" android:layout_margintop= "10DP" Android:indeter Minate= "true" android:indeterminatedrawable= "@drawable/indeterminate_drawable" android:indeterminateduration = "android:visibility=" "Invisible"/> <textview android:layout_width= "Wrap_content" Android        oid:layout_height= "Wrap_content" android:layout_marginbottom= "10DP" android:layout_marginleft= "15DP" android:layout_margintop= "10DP" android:text= "load More" android:textcolor= "#aa000000" android:textsize= "2 0SP "/></linearlayout>

2. Initialize the session Footerview in the custom ListView and add it to the bottom of the ListView

/** * Initialize Footerview */private void Initfooterview () {Footerview = View.inflate (GetContext (), R.layout.layout_footer, NULL),//Get the Custom component's width-height footerview.measure (0, 0); footerviewheight = Footerview.getmeasuredheight ();// Hide the head footerview.setpadding (0,-footerviewheight, 0, 0);//Add Footerview to the bottom of the ListView Addfooterview (Footerview);}

3, let the custom view, and implement Onscrolllistener and rewrite, in the initialization method to invoke the listener

private void Init () {Setonscrolllistener (this);                .....       }


Defines a Boolean type that is used to determine whether to load more

Private Boolean isloadingmore = false; //is currently in the load more

/** * Scrollstate Value: * 0 = Scroll_state_idle: Idle state, is the finger release * 1 = scroll_state_touch_scroll:   finger touch Swipe, is to press to slide * 2 = SCROLL _state_fling:  Quick swipe to release */@Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {//LOG.E (" Main ", Scrollstate +"); When the finger is released and the item in the ListView is the last bar, the    Footerview//getcount gets the total number of bars in the ListView if ( Scrollstate = = onscrolllistener.scroll_state_idle&& getlastvisibleposition () = = (GetCount ()-1) &&! Isloadingmore) {Isloadingmore = true;footerview.setpadding (0, 0, 0, 0);//Move the list to the specified position place SetSelection (GetCount ()) ///If the listener is not empty  then the call loads more methods if (Listener!=null) {Listener.onloadingmore ();}}} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) {}


4, add a load more methods in the interface

Public interface onrefreshlistener{//down refreshed when calling void Onpullrefresh ();//load more void Onloadingmore ();}


5. Rewrite in mainactivity--load more methods

private void InitData () {..... Reflv.setonrefreshlistener (New Onrefreshlistener () {public void Onpullrefresh () {//LOG.E ("mainactivity", "Enter the refreshing state, The server data should be requested at this time ");//require networking to request server data and update uirequestdatafromserver (FALSE);} @Overridepublic void Onloadingmore () {requestdatafromserver (true);}}); /** * Simulates requesting data from the server * @param isloadingmore  is used to differentiate whether to load more data  or drop-down refreshes */private void Requestdatafromserver (Final boolean is Loadingmore) {new Thread () {public void run () {/////Impersonate the request service for a length of time systemclock.sleep (3000);//Add Data to head if (Isloadingmore) { List.add ("Load more data-1"), List.add ("Load more data-2"), List.add ("Load More data-3");} else {list.add (0, "drop-refreshed data");} Update uihandler.sendemptymessage (0);};}. Start ();}


6, modify the Completerefresh () in the custom view, reset the Footerview status
/** * Complete Refresh reset to drop-down refresh status * Call the method in the UI thread after data update adapter is requested  */public void Completerefresh () {if (Isloadingmore) {// Resets the Footerview state footerview.setpadding (0,-footerviewheight, 0, 0); isloadingmore = false;} else{//headerview Status//Hidden headerviewheaderview.setpadding (0,-headerviewheight, 0, 0);//Status Change CurrentState = PULL_ Refresh;//progressbar Hidden Pb_rotate.setvisibility (view.invisible);//Picture shows iv_arrow.setvisibility (View.VISIBLE); tv_ State.settext ("drop-down Refresh"); Tv_time.settext ("Last refreshed:" + getcurrenttime ());}}



The total code

Custom View

public class Refreshlistview extends ListView implements Onscrolllistener {private View headerview;//headerviewprivate int headerviewheight;//headerviewheightprivate View footerview;//footerviewprivate int footerviewheight;// footerviewheightprivate int DownY;//press the Y coordinate point when the private final int pull_refresh = 0;//The state of the refresh is private final int release_ref Resh = 1;//Release the refreshed state private final int refreshing = 2;//The state being refreshed private int currentstate = Pull_refresh;private ImageView iv_a Rrow;private ProgressBar pb_rotate;private TextView tv_state;private TextView tv_time;private boolean isloadingmore = FA Lse;//is currently in the load more//Rotation animation private rotateanimation upanimation, downanimation; Public Refreshlistview (context context, AttributeSet Attrs) {Super (context, attrs); init ();} Public Refreshlistview (Context context) {super (context); init ();} /** * Initialize data in listview */private void init () {Setonscrolllistener (this);//Initialize Headerviewinitheaderview ();// Initialize animation initrotateanimation ();//Initialize Footerviewinitfooterview ();} /** * Initializing animations*/private void Initrotateanimation () {//Up animation upanimation = new Rotateanimation (0, -180, rotateanimation.relative_to_ Self, 0.5f,rotateanimation.relative_to_self, 0.5f); upanimation.setduration; Upanimation.setfillafter (true); /Down Animation downanimation = new Rotateanimation ( -180, -360,rotateanimation.relative_to_self, 0.5f, Rotateanimation.relative_to_self, 0.5f);d ownanimation.setduration (+);d Ownanimation.setfillafter (true); /** * Add a headerview */private void Initheaderview () {//Get the layout of the head Headerview = view.inflate (GetContext (), R.layout.layout_ header, null); Iv_arrow = (ImageView) Headerview.findviewbyid (r.id.iv_arrow);p b_rotate = (ProgressBar) Headerview.findviewbyid (r.id.pb_rotate); tv_state = (TextView) Headerview.findviewbyid (r.id.tv_state); tv_time = ( TextView) Headerview.findviewbyid (r.id.tv_time);//Gets the width of the custom component Headerview.measure (0, 0); headerviewheight = Headerview.getmeasuredheight ();//Hide the head headerview.setpadding (0,-headerviewheight, 0, 0);// Add head to Refreshlistview Addheaderview (HeadervieW);} /** * Initialize Footerview */private void Initfooterview () {Footerview = View.inflate (GetContext (), R.layout.layout_footer, NULL),//Get the Custom component's width-height footerview.measure (0, 0); footerviewheight = Footerview.getmeasuredheight ();// Hide the head footerview.setpadding (0,-footerviewheight, 0, 0);//Add Footerview to the bottom of the ListView Addfooterview (Footerview);} @Overridepublic boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:downY = ( int) ev.gety (); Break;case motionevent.action_move://If it is in a refresh, it is not allowed to operate if (CurrentState = = refreshing) {break;} Gets the size of the move int delaY = (int) (Ev.gety ()-DownY);//Calculates a new headerviewheightint paddingtop =-headerviewheight + delay;if (padd Ingtop >-headerviewheight && getfirstvisibleposition () = = 0) {headerview.setpadding (0, paddingtop, 0, 0); if ( Paddingtop >= 0 &¤tstate = = Pull_refresh) {//drop-down Refresh status Enter release refresh status CurrentState = Release_refresh;refreshheaderview ();} else if (Paddingtop < 0&& CurrentState = = Release_refresh) {//Release refresh state into drop-down refresh status CurrEntstate = Pull_refresh;refreshheaderview ();} Intercepting the touchmove and not letting the ListView handle the Move event will cause the ListView to not slide return true; Break;case MotionEvent.ACTION_UP:if (CurrentState = = Pull_refresh) {//Hide headerviewheaderview.setpadding (0,- Headerviewheight, 0, 0);} else if (CurrentState = = Release_refresh) {headerview.setpadding (0, 0, 0, 0); currentstate = Refreshing;refreshheaderview ();//Analog delay//new Handler (). postdelayed (New Runnable () {////@Override//public void Run () {//completerefresh ();//}//}, if (listener! = null) {Listener.onpullrefresh ();}} break;} return super.ontouchevent (EV);} /** * Based on currentstate to update headerview */private void Refreshheaderview () {switch (currentstate) {case Pull_refresh://dropdown refreshed Status Tv_state.settext ("drop-down Refresh"); Iv_arrow.startanimation (downanimation); Break;case Release_refresh://Release Refresh status tv_  State.settext ("release Refresh"); Iv_arrow.startanimation (upanimation); Break;case refreshing://State being refreshed//clear animation may not be completed So you need to clear the animation iv_arrow.clearanimation ();//Make the icon hide iv_arrow.setvisibility (view.invisible);//progressbar Show Visible PB_rotate.setvisibility (view.visible); Tv_state.settext ("refreshing ..."); /** * Complete Refresh reset to drop-down refresh status * Call the method in the UI thread after data update adapter is requested */public void Completerefresh () {if (Isloadingmore) {//Reset Footerview State Footerview.setpadding (0,-footerviewheight, 0, 0); isloadingmore = false;} else{//headerview Status//Hidden headerviewheaderview.setpadding (0,-headerviewheight, 0, 0);//Status Change CurrentState = PULL_ Refresh;//progressbar Hidden Pb_rotate.setvisibility (view.invisible);//Picture shows iv_arrow.setvisibility (View.VISIBLE); tv_ State.settext ("drop-down Refresh"); Tv_time.settext ("Last refreshed:" + getcurrenttime ());}} /** * Get current time * @return */private String getcurrenttime () {SimpleDateFormat format = new SimpleDateFormat ("Yy-mm-dd HH:mm:ss "); return Format.format (New Date ());} /** * Define refresh Listener interface to handle processing of business logic requests during refresh * @author Denny * @date 2016-4-26 */public interface onrefreshlistener{//down refresh call void O Npullrefresh ();//load more void Onloadingmore ();} Private Onrefreshlistener listener;public void Setonrefreshlistener (Onrefreshlistener listener) {This.listener = ListeneR;} /** * Scrollstate Value: * 0 = Scroll_state_idle: Idle state, is the finger release * 1 = scroll_state_touch_scroll: Finger touch Swipe, is to press to slide * 2 = scroll_s Tate_fling: Quick swipe to release */@Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {//log.e ("main", Scrollstate + ""); when the finger is released and the item in the ListView is the last bar, display footerview//getcount gets the total number of bars in the listview if (scrollstate = = onscrolllistener.scroll_state_idle&& getlastvisibleposition () = = (GetCount ()-1) &&!isloadingmore) {  Isloadingmore = true;footerview.setpadding (0, 0, 0, 0);//Move the list to the specified position at SetSelection (GetCount ());//If the listener is not empty The call loads more methods if (Listener!=null) {Listener.onloadingmore ();}}} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) {}}




Mainactivity


public class Mainactivity extends Activity {private Refreshlistview reflv;private arraylist<string> list = new Array List<string> ();p rivate myadapter myadapter;private Handler Handler = new Handler () {public void Handlemessage ( Android.os.Message msg) {//Update UI myadapter.notifydatasetchanged ();//Reset Status Reflv.completerefresh ();};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Initview (); InitData ();} /** * Initialize view */private void Initview () {Setcontentview (r.layout.activity_main); reflv = (Refreshlistview) findViewById ( r.id.reflv);} /** * Initialize data */private void InitData () {for (int i = 0; i < i++) {List.add ("ListView Original data:" + i);}   Get the layout of the head//final View headerview = view.inflate (Mainactivity.this,//r.layout.layout_header, null);//1, the first The way to get the height of the automatically loaded view is to use the Listening method////using inflate is asynchronous to get to the height of the loading component need to use Getviewtreeobserver to listen// Headerview.getviewtreeobserver (). Addongloballayoutlistener (//new Ongloballayoutlistener () {////@Override//pubLIC void Ongloballayout () {//////to remove the//headerview.getviewtreeobserver () first. Removeglobalonlayoutlistener (This) //////gets the height of the head layout//int headerviewheight = Headerview.getheight ();////hides the head//headerview.setpadding (0,- Headerviewheight, 0, 0);//reflv.addheaderview (Headerview);//}//});//The first to obtain a dynamic custom component of the wide-height//headerview.measure (0, 0); The automatic notification system gets the height and width//int headerviewheight = Headerview.getmeasuredheight ();////hides the head//headerview.setpadding (0,- Headerviewheight, 0, 0);//reflv.addheaderview (headerview); myadapter = new Myadapter (); Reflv.setadapter (MyAdapter); Reflv.setonrefreshlistener (New Onrefreshlistener () {public void Onpullrefresh () {//LOG.E ("mainactivity", "Enter the refreshing state, The server data should be requested at this time ");//require networking to request server data and update uirequestdatafromserver (FALSE);} @Overridepublic void Onloadingmore () {requestdatafromserver (true);}}); /** * Simulates requesting data from the server * @param isloadingmore is used to differentiate between loading more data or refreshing */private void Requestdatafromserver (Final boolean isloading More) {new Thread () {public void run () {////Impersonation request service One length of time Systemclock.sleEP (3000);//Add Data to head if (isloadingmore) {list.add ("load more data-1"), List.add ("Load more Data 2"), List.add ("Load More data-3");} else {list.add (0, "drop-refreshed data");} Update uihandler.sendemptymessage (0);};}. Start ();} Class Myadapter extends Baseadapter {@Overridepublic int getcount () {return list.size ();} @Overridepublic Object getItem (int position) {return null;} @Overridepublic long Getitemid (int position) {return 0;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {TextView TV = new TextView (mainactivity.th is); tv.setpadding (tv.settextsize); Tv.settext (List.get (position)); return TV;}}}




Android Learning (45)--custom Control (9) drop-down Refresh (add footer)

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.