"Android Notes" recyclerview+swiperefreshlayout example

Source: Internet
Author: User
Tags recyclerview android

through this article one will learn:Basic usage of 1.RecyclerView; 2. Basic usage of swiperefreshlayout; 3. Add a response event for the Recyclerview item.
Recyclerview simple, it is used to replace the traditional ListView,Recyclerview is more flexible, and can be combined with animation, you can easily add a variety of animation effects for each item, in addition, Recyclerview forced to use Viewholder mode, can improve performance.


Step: 1. Add dependencies:

Compile ' com.android.support:recyclerview-v7:21.0.0 ' compile ' com.android.support:support-v4:22.0.0 '
2. Writing activity layouts:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "HTTP://SCHEMAS.A                Ndroid.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent " tools:context= "Com.taobao.recyclerviewwithrefresh.ui.activity.GridActivity" > <android.support.v4.wi Dget. Swiperefreshlayout android:id= "@+id/refreshlayout_grid" android:layout_width= "Match_parent" android:l ayout_height= "Match_parent" > <android.support.v7.widget.recyclerview android:id= "@+id/recyclerView _grid "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:s crollbars= "Vertical" ></android.support.v7.widget.RecyclerView> &LT;/ANDROID.SUPPORT.V4.WIDGET.SWIP Erefreshlayout></relativelayout>
3. Writing the layout of each item:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "              android:orientation=" horizontal "              android:layout_width=" match_parent "              xmlns:tools="/http/ Schemas.android.com/tools "              android:layout_height=" 50DP ">    <imageview        android:src=" @mipmap/ic_ Launcher "        android:padding=" 5DP "        android:layout_width=" wrap_content "        android:layout_height=" Wrap_ Content "/>    <textview        android:id=" @+id/tv "        android:layout_width=" Wrap_content "        Android : textsize= "18SP"        android:gravity= "center"        android:layout_height= "match_parent"        tools:text= "ss"/ ></LinearLayout>
4. Data Source:
Package Com.taobao.recyclerviewwithrefresh.data;import java.util.arraylist;import java.util.list;/** * Created by ROWANDJJ on 2015/3/24. */public class datasource{public    static final list<string> generatedata (int size)    {        if (size <= 0)            return null;        list<string> datas = new arraylist<> ();        for (int i = 0; i < size; i++)        {            Datas.add ("This is List data" +i);        }        return datas;}    }
5. Separator bar:
Package Com.taobao.recyclerviewwithrefresh.ui.adapter;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.drawable.drawable;import Android.support.v7.widget.recyclerview;import android.view.view;/** * Created by ROWANDJJ on 2015/3/24. */public class Myitemdecoration extends recyclerview.itemdecoration{private static final int[] Attrs = {Android.    R.attr.listdivider};    Private drawable Mdivider;        Public Myitemdecoration (Context context) {TypedArray array = context.obtainstyledattributes (attrs);        Get separator Bar Mdivider = array.getdrawable (0);    Array.recycle (); } @Override public void Ondrawover (Canvas C, Recyclerview parent, recyclerview.state state) {Super.ondraw        Over (c, parent, state);        int count = Parent.getchildcount ();        int left = Parent.getpaddingleft ();        int right = Parent.getwidth ()-parent.getpaddingright (); for (int i = 0; I < count;            i++) {View v = parent.getchildat (i);            Recyclerview.layoutparams params = (recyclerview.layoutparams) v.getlayoutparams ();            int top = V.getbottom () + Params.bottommargin;            int bottom = top + mdivider.getintrinsicheight ();            Mdivider.setbounds (Left,top,right,bottom);        Mdivider.draw (c); }    }}
6. Write the data adapter and add a click response event for it
Package Com.taobao.recyclerviewwithrefresh.ui.adapter;import Android.support.v7.widget.recyclerview;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.TextView ; Import Com.taobao.recyclerviewwithrefresh.r;import java.util.list;/** * Created by ROWANDJJ on 2015/3/24. * */public class Mainrecycleradapter extends recyclerview.adapter<mainrecycleradapter.viewholder>{private List    <String> datas = null;    Private Onitemclicklistener Mlistener;    public void Setonitemclicklistener (Onitemclicklistener listener) {This.mlistener = listener;    } public Mainrecycleradapter (list<string> datas) {this.datas = datas; } @Override Public Viewholder oncreateviewholder (viewgroup parent, int viewtype) {final View Itemview = L        Ayoutinflater.from (Parent.getcontext ()). Inflate (R.layout.item, parent, false);        Itemview.setonclicklistener (New View.onclicklistener () {    @Override public void OnClick (View v) {if (Mlistener! = null) {                Mlistener.onitemclick (V, (String) Itemview.gettag ());        }            }        });    return new Viewholder (Itemview); } @Override public void Onbindviewholder (viewholder holder, int position) {String s = datas.get (position)        ;        Holder.binddata (s);    Holder.itemView.setTag (s);    } @Override public int getitemcount () {return datas.size (); /** * * * */public void Additems (list<string> items) {if (items = null) r        Eturn;        This.datas.addAll (0, items);    this.notifyitemrangeinserted (0, Items.size ());    } public interface Onitemclicklistener {public void Onitemclick (View view,string data);        } static class Viewholder extends Recyclerview.viewholder {private TextView mcontent; Public Viewholder (VieW Itemview) {super (Itemview);        Mcontent = (TextView) Itemview.findviewbyid (r.id.tv);        } public void Binddata (String s) {if (s! = null) Mcontent.settext (s); }    }}

Recyclerview does not provide callbacks like Onitemclicklistener, here we implement a ...

7. Main Page code:
Package Com.taobao.recyclerviewwithrefresh.ui.activity;import Android.content.intent;import Android.os.AsyncTask; Import Android.os.bundle;import Android.support.v4.widget.swiperefreshlayout;import Android.support.v7.app.actionbaractivity;import Android.support.v7.widget.linearlayoutmanager;import Android.support.v7.widget.recyclerview;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.widget.toast;import Com.taobao.recyclerviewwithrefresh.r;import Com.taobao.recyclerviewwithrefresh.data.datasource;import Com.taobao.recyclerviewwithrefresh.ui.adapter.myitemdecoration;import Com.taobao.recyclerviewwithrefresh.ui.adapter.mainrecycleradapter;import Java.util.arraylist;import java.util.list;/** * 1.RecyclerView Basic usage * LayoutManager * itemanimator * itemdecoration * * Recyclervi ew. Adapter * Recyclerview.viewholder * * 2.SwipeRefreshLayout Usage * * 3. Add a response event to each item of Recyclerview * 4. Control Recyclerview Scroll to a specific location: Recyclerview#scrollToposition * * * */public class Mainactivity extends Actionbaractivity implements swiperefreshlayout.onrefreshlistener{    Private Recyclerview Mrecyclerview;    Private Swiperefreshlayout mrefreshlayout;    Private Linearlayoutmanager Mlinearlayoutmanager;    Private Mainrecycleradapter Madapter;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mrecyclerview = (Recyclerview) Findviewbyid (R.id.recyclerview);        Mrefreshlayout = (swiperefreshlayout) Findviewbyid (r.id.refreshlayout);        Mrefreshlayout.setonrefreshlistener (this);        Mlinearlayoutmanager = new Linearlayoutmanager (this);        Madapter = new Mainrecycleradapter (Datasource.generatedata (20));        Mrecyclerview.setadapter (Madapter);        Each item is highly consistent and can be set to true to improve performance mrecyclerview.sethasfixedsize (true);        Mrecyclerview.setlayoutmanager (Mlinearlayoutmanager); Divider Line MRecYclerview.additemdecoration (New Myitemdecoration (this)); Add response event Madapter.setonitemclicklistener for each item (new Mainrecycleradapter.onitemclicklistener () {@ Override public void Onitemclick (view view, String data) {Toast.maketext (mainactivit            Y.this, "Data:" + data, Toast.length_short). Show ();    }        });    } @Override public void Onrefresh () {new Updatetask (). Execute ();  } private class Updatetask extends Asynctask<void,void,list<string>> {@Override protected             List<string> doinbackground (Void ... params) {try {thread.sleep (2000);            } catch (Interruptedexception e) {e.printstacktrace ();            } list<string> strings = new arraylist<> ();            Strings.add ("New Data 1");            Strings.add ("New Data 2");            Strings.add ("New Data 3"); StrinGs.add ("New Data 4");        return strings; } @Override protected void OnPostExecute (list<string> strings) {Madapter.additems (s           Trings);           Notification Refresh complete mrefreshlayout.setrefreshing (false);        Scroll to column header---> This is a handy API that can be slid to the specified position mrecyclerview.scrolltoposition (0); }} @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.menu_mai        n, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. T He action Bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid (); Noinspection simplifiableifstatement if (id = = R.id.action_grid) {this.startactivity (new Inten            T (this, gridactivity.class));    return true;    }else if (id = = r.id.action_settings) {toast.maketext (Mainactivity.this, "Run ...", Toast.length_shor            T). Show ();        return true;    } return super.onoptionsitemselected (item); }}






"Android Notes" recyclerview+swiperefreshlayout example

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.