Swiperefreshlayout+recyclerview implementation Drop-down Refresh Pull Auto Load _ Mirrors Blog

Source: Internet
Author: User
Tags addall xdiff lenovo

In the actual development, in order to save the development cycle, drop-pull refresh load usually take the use of a number of third-party libraries, typically with Pulltorefresh,xlistview, and so on, there is Google recommended Swiperefreshlayout, unfortunately did not pull the load function, Need to implement a pull-loaded foot view, coupled with the current replacement of ListView Recyclerview+cardview frequency also come also high, have to say, CardView effect is really good-looking, a small card, user experience good, I like It ... Nonsense not to say, Ben Theme. I had a little bit of fun today. Swiperefreshlayout+recyclerview implement Drop-down refresh pull automatically load.
My original idea is: First use Recyclerview add different item layout, above is a carousel Viewpager, the following is a list of data, when the bottom of the time, can automatically load more, of course, to add a personalized view at the end of the display is loading, is the foot view.

First look at how Recyclerview loaded the different item, through the Getitemviewtype implementation, note: The successor is Recyclerview.adapter.
1. Set 3 constants, respectively, of the Viewpager section, the middle of the list data section, and the bottom of the Loading foot section:

private static final int item_header = 0;
    private static final int item_item = 1;
    private static final int item_load_footer = 2;

Three pull loads for more display states:

Pull load more public
    static final int pullup_load_more=0;
    Loading ...
    public static final int isloading=1;
    The display state of the pull load, initially 0
    private int load_more_status=0;

Adapter set in a method to facilitate the activity call to change the loading state to display different loading information (pull load more, load ...) ):

public void changemorestatus (int status) {
        load_more_status=status;
        Notifydatasetchanged ();
    }

2. Create Viewholder:

@Override public
    Recyclerview.viewholder Oncreateviewholder (viewgroup parent, int viewtype) {
        if (viewtype== Item_header) {
            View view = Layoutinflater.from (context). Inflate (r.layout.item_header,parent,false);
            return new Headerviewholder (view);
        } else if (Viewtype==item_item) {
            View view = Layoutinflater.from (context). Inflate (R.layout.item_item,parent,false );
            return new Itemviewholder (view);
        } else if (viewtype==item_load_footer) {
            View view = Layoutinflater.from (context). Inflate (R.layout.refresh_footer , parent,false);
            return new Loadfooterviewholder (view);
        }
        return null;
    }

3. Binding Data:

@Override public void Onbindviewholder (Recyclerview.viewholder holder, final int position) {if (holder instance
        of Itemviewholder) {((itemviewholder) holder). Mtextview.settext (Mlistdata.get (position-1)); 
            }else if (holder instanceof Loadfooterviewholder) {loadfooterviewholder footer = (loadfooterviewholder) holder; Switch (load_more_status) {case PULLUP_LOAD_MORE:footer.progressbar.setVi
                    Sibility (View.gone);
                    Footer.loadmore_text.setText ("Pull load more");
                Break
                    Case ISLOADING:footer.progressbar.setVisibility (view.visible);
                    Footer.loadmore_text.setText ("Loading ...");
            Break }//List data Click event Monitor, note: Here the position is more position+1 than normal because of the extra head view Holder.itemView.setOnClickListener ( New View.onclicklistener () {@Override public void OnClick (View v) {
                Toast.maketext (Context, "Click on position" +position, Toast.length_short). Show ();
    }
        }); }

Note: This only deals with the intermediate list of data, the Viewpager part of the data is not processed here.

4. Get the number of item:

@Override public
    int GetItemCount () {return
        mlistdata.size () +2;
    }

Description: +2 is because in addition to the normal list data, but also add a head and foot view

5.ItemView Type:

@Override public
    int getitemviewtype (int position) {
        if (position==0) {return
            item_header;
        } else if (position==mlistdata.size () +1) {return
            item_load_footer;
        } else {return
            item_item;
        }
    }

Description: The first item adds a Viewpager, the last item adds a loaded foot view, and the rest of the middle is the normal list data.

The following three view inner classes:

Class Headerviewholder extends recyclerview.viewholder{private Viewpager Mviewpager;
        Private LinearLayout LinearLayout;
        Private imageview[] points;
                Private Handler Handler = new Handler () {@Override public void Handlemessage (msg) {
                Super.handlemessage (msg);
                Mviewpager.setcurrentitem (Mviewpager.getcurrentitem () +1);
            Handler.sendemptymessagedelayed (1,3000);
        }
        };
            Public Headerviewholder (View Itemview) {super (Itemview);
            Mviewpager = (Viewpager) Itemview.findviewbyid (R.id.viewpager);
            LinearLayout = (linearlayout) Itemview.findviewbyid (r.id.linearlayout);
            The following two sentences should be called before Setadapter, otherwise the first load of the last picture will appear Mviewpager.setcurrentitem (INTEGER.MAX_VALUE/2);
            Handler.sendemptymessagedelayed (1,3000);
            Mviewpager.setadapter (New Myviewpageradapter (context, imagesurl)); Initpoint ();  Mviewpager.setonpagechangelistener (New Viewpager.onpagechangelistener () {@Override public void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {} @ Override public void onpageselected (int position) {for (int i=0;i<imagesurl.length; i++) {if (position%imagesurl.length==i) {Points[i].setimageresource (R.D
                        Rawable.point_focus);
                        }else {points[i].setimageresource (r.drawable.point_normal); @Override public void onpagescrollstatechanged (
        int state) {}});
            private void Initpoint () {points = new imageview[imagesurl.length]; for (int i=0;i<points.length;i++) {POInts[i] = (ImageView) linearlayout.getchildat (i);
        } points[0].setimageresource (R.drawable.point_focus);
        } class Itemviewholder extends recyclerview.viewholder{private TextView mtextview;
            Public Itemviewholder (View Itemview) {super (Itemview);
        Mtextview = (TextView) Itemview.findviewbyid (R.id.textview); } class Loadfooterviewholder extends recyclerview.viewholder{private ProgressBar Loarmore_progressbar
        ;
        Private TextView Loadmore_text;
            Public Loadfooterviewholder (View Itemview) {super (Itemview);
            Loarmore_progressbar= (ProgressBar) Itemview.findviewbyid (R.id.loarmore_progressbar);
        Loadmore_text = (TextView) Itemview.findviewbyid (R.id.loadmore_text); }
    }

Note: I can see that the data of my head Viewpager are all handled in the internal class.
In the middle is the list data, the 3rd step binding Data There processing, the bottom is the load foot view, in the above binding data has set the dynamic display different loading state.

OK so the data adapter is done.
Drop-down Refresh has Google's swiperefreshlayout implementation, how to detect when the end of the need to load new data. The method is as follows:

Slide up, when the end of the slide, there is a trend of sliding, loading more mrecyclerview.setonscrolllistener (new Recyclerview.onscrolllistener () {@Override public void onscrollstatechanged (Recyclerview recyclerview, int newstate) {Super.onscrollstat
                Echanged (Recyclerview, newstate); 
                    if (!mswiperefreshlayout.isrefreshing ()) {int lastvisibleitem = mmanager.findlastvisibleitemposition ();
                        if (Newstate==recyclerview.scroll_state_idle&&lastvisibleitem+1==madapter.getitemcount ()) { Call the Changemorestatus method in adapter to change the display status of the loaded foot view as: Loading ... madapter.changemorest
                        ATUs (myrecyclerviewadapter.isloading); New Handler (). postdelayed (New Runnable () {@Override public void R
                                Un () {mlistdata.addall (mlistloaddata);
                  Madapter.notifydatasetchanged ();              When the data is loaded, the display status of the loaded foot view is restored: Pull load more madapter.changemorestatus (Myrecyclerviewad Apter.
                            Pullup_load_more);
                    }},3000); }
                }
            }
        });

Description: Recyclerview has a Setonscrolllistener method, loading more logic in here to achieve, specifically do not say, look at the understanding.

Complete code for Mainactivity:

Package Com.example.lenovo.recyclerview;
Import android.app.Activity;
Import Android.graphics.Color;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.support.v4.widget.SwipeRefreshLayout;
Import Android.support.v7.widget.LinearLayoutManager;
Import Android.support.v7.widget.RecyclerView;
Import java.util.ArrayList;
Import java.util.List;

Import Adapter.myrecyclerviewadapter;
    public class Mainactivity extends activity {private Recyclerview Mrecyclerview;
    Private Swiperefreshlayout mswiperefreshlayout;
    Private Linearlayoutmanager Mmanager;
    Private Myrecyclerviewadapter Madapter;
    Private list<string> Mlistdata;
    Private list<string> Mlistloaddata;
            Private string[] Imagesurl = {"Http://bbs.uc.cn/data/attachment/forum/201302/17/163510xsv14x35i9ix41i0.jpg", "Http://p3.so.qhimg.com/t0121ddd5bc66dcc9e8.jpg", "http://p3.so.qhimg.com/t0181e8d7355386f79d.jpg" , "http://bbs.liebao.cn/data/aTtachment/forum/201210/25/182447qee2e922myyw8y8m.jpg "};
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
        Setcontentview (R.layout.activity_main);
        InitData ();

        Initview (); 
            Drop-down Refresh Mswiperefreshlayout.setonrefreshlistener (new Swiperefreshlayout.onrefreshlistener () {@Override public void Onrefresh () {new Handler (). postdelayed (New Runnable () {@Ove
                    Rride public void Run () {mswiperefreshlayout.setrefreshing (false);
            }},5000);

        }
        }); Slide up, and when the end is slipping, there is a tendency to slide up, loading more mrecyclerview.setonscrolllistener (new Recyclerview.onscrolllistener () {@O Verride public void onscrollstatechanged (Recyclerview recyclerview, int newstate) {SUPER.ONSC
        Rollstatechanged (Recyclerview, newstate);        if (!mswiperefreshlayout.isrefreshing ()) {int lastvisibleitem = Mmanager.findlastvisibleitempos
                    Ition ();
                        if (Newstate==recyclerview.scroll_state_idle&&lastvisibleitem+1==madapter.getitemcount ()) { Call the Changemorestatus method in adapter to change the display status of the loaded foot view as: Loading ... madapter.changemorestatus (Myrecyclerviewad Apter.
                        isloading); New Handler (). postdelayed (New Runnable () {@Override public void R
                                Un () {mlistdata.addall (mlistloaddata);
                                Madapter.notifydatasetchanged (); When the data is loaded, the display status of the loaded foot view is restored: Pull load more madapter.changemorestatus (myrecyclerviewadapter.pullup_l
                            Oad_more);
                    }},3000);
    }
                }
            }
        });

   } /** * Initialization data */private void InitData () {mlistdata = new arraylist<> ();
        Mlistloaddata = new arraylist<> ();
            for (int i=0;i<30;i++) {mlistdata.add ("data" +i);
        Mlistloaddata.add ("New Loaded Data" +i); }/** * Initialize view */private void Initview () {Mrecyclerview = (Recyclerview) Findviewbyid (
        R.id.recyclerview);
        Mmanager = new Linearlayoutmanager (this);
        Mrecyclerview.setlayoutmanager (Mmanager);
        Madapter = new Myrecyclerviewadapter (This,mlistdata,imagesurl);
        Mrecyclerview.setadapter (Madapter);
        Mswiperefreshlayout = (swiperefreshlayout) Findviewbyid (r.id.swiperefreshlayout);
    Up to 4 colors of mswiperefreshlayout.setcolorschemecolors (color.blue,color.red);
 }
}

Where necessary, there are explanations, and there will be no more to repeat. Get. Run. A look at the effect is still possible, on the pull down to pull the load to play a bit, when I manually slide the viewpager of the wheel, found that some not smooth, pull down a refreshing feeling to be pulled down, found that there are conflicts:
Baidu a bit, found that there are many people have this problem, the solution online also a lot of:
Rewrite swiperefreshlayout.

So, rewrite the code as follows:

Package View;
Import Android.content.Context;
Import Android.support.v4.widget.SwipeRefreshLayout;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;

Import android.view.ViewConfiguration;
 /** * Created by Lenovo on 2016/7/9.
    * * public class Myswiperefreshlayout extends Swiperefreshlayout {private int mtouchslop;
    The x coordinate of the last touch is private float mprevx;
        Public Myswiperefreshlayout (context, AttributeSet attrs) {Super (context, attrs);
    The shortest distance that triggers the move event, and does not trigger the mobile control Mtouchslop = Viewconfiguration.get (context) if it is less than this distance. Getscaledtouchslop ();
            @Override public boolean onintercepttouchevent (Motionevent event) {switch (event.getaction ()) {
                Case MotionEvent.ACTION_DOWN:mPrevX = Event.getx ();
            Break
                Case MotionEvent.ACTION_MOVE:final Float eventx = Event.getx ();
                float Xdiff = Math.Abs (EVENTX-MPREVX); LOG.D ("Refresh "," move----"+ Eventx +" "+ Mprevx +" "+ mtouchslop);
                Increase the tolerance by 60, so that the Drop-down refresh can trigger if (Xdiff > Mtouchslop +) {return False when it is vertically sliding;
    } return Super.onintercepttouchevent (event);
 }
}

Run again. Get. Perfect..

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.