Advanced use of the Recyclerview universal adapter

Source: Internet
Author: User
Tags return tag

Preface

Bloggers because of the frequent use of the project in the V7 package Recyclerview to replace the ListView list display, so the time based on the ListView general adapter principle, to Recyclerview also wrote a universal adapter mainly supports the following features:

1. Support the item's click event, in the case of multi-layout can specify the effective itemtype

2. Support the Click event of the control in item (bloggers feel Innovative), in the case of multi-layout can be specified in effect itemtype

3. Support to add and remove the head (bloggers do not write the method to add the tail, in fact, and add the head of the method is similar, if you need to refer to the change it)

4. Support multi-layout (in fact, this is not the blogger write function, but the self-brought, the following will be stated)

All of the above functions are done by the universal adapter and do not make any changes to the Recyclerview itself

Then the blogger will first take you to see how it is used, see if he is to improve our development efficiency!


XML Layout

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    xmlns:tools=" Http://schemas.android.com/tools "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    tools:context= "com.yoursecondworld.recyclerviewdemo.MainActivity" >    <android.support.v7.widget.recyclerview        android:id= "@+id/rv"        android:layout_width= "Match_ Parent "        android:layout_height=" match_parent "/>    </RelativeLayout>

Number One (an upright, simple list that shows the names of people)

public class Mainactivity extends Appcompatactivity {//List of presentation data private Recyclerview RV = null;    Data to be displayed private list<string> data = new arraylist<string> ();        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        The displayed data is falsified for (int i = 0; i < i++) {Data.add ("item:" + i);        }//Search Control RV = (Recyclerview) Findviewbyid (R.ID.RV);        Create a linear layout manager and set Linearlayoutmanager LayoutManager = new Linearlayoutmanager (this);        Layoutmanager.setorientation (linearlayoutmanager.vertical);        Rv.setlayoutmanager (LayoutManager); commonrecyclerviewadapter<string> adapter = new Commonrecyclerviewadapter<string> (this, data) {@Ov Erride public void Convert (Commonrecyclerviewholder h, String entity, int position) {H.settext ( Android.     R.ID.TEXT1, entity);       }//Returns the ID of the item layout @Override public int getlayoutviewid (int viewtype) { Return Android.            R.layout.simple_list_item_1;        }        };    Set adapter Rv.setadapter (adapter); }}

You can see that the adapter is coming out of the inner class, because the code is a little less so it's written like this, you'd better create a class in the project.

The code is simple, is to let Recyclerview vertical display of the data, the layout of the item temporarily used the system

effect


Can see that the display is not a bit of a problem, then I want to implement the item click what?

Achieve the Click effect of item

Adapter.setonrecyclerviewitemclicklistener (New Commonrecyclerviewadapter.onrecyclerviewitemclicklistener () {        @Override public        void Onitemclick (View v, int position) {               Toast.maketext (mainactivity.this, "You clicked on the" + Position + "item", Toast.length_short). Show ();        });
Is it the same as the ListView item listener? Change the name of the method, right?

Click the item effect


You can see that the Click event takes effect

Multi-layout demo

We need an entity object because of the need to display

Entity

public class Demoentity {    //If you have this description you need to use the tag entry    private String tag;    If there is this description to use the Item entry    private String name;    Public demoentity (string tag, string name) {        This.tag = tag;        this.name = name;    }    Public String Gettag () {        return tag;    }    public void Settag (String tag) {        This.tag = tag;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }}

Note that if there is a tag property, there is no Name attribute

Since it is multi-layout, then two or more layouts, here with two layouts for example

XML (Tagitem)

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" wrap_content ">    <textview        android:id= "@+id/tv_tag"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android:textcolor= "#0000FF"        android:textsize= "24DP"/></relativelayout>

XML (Nameitem)

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent ">    <textview        android:id= "@+id/tv_name"        android:layout_width= "wrap_content"        android:layout_height= "wrap_content "        android:layout_marginleft=" 16DP "        android:textsize=" 16DP "/></relativelayout>

Then we need one more method in the adapter, first look at the code

Modified Activity Code

public class Mainactivity extends Appcompatactivity {//List of presentation data private Recyclerview RV = null;    Data to be displayed private list<demoentity> data = new arraylist<demoentity> ();        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Show the data fake Data.add (new demoentity ("A", null));        Data.add (new demoentity (NULL, "A-Da"));        Data.add (new demoentity (null, "Auntie"));        Data.add (New Demoentity ("C", null));        Data.add (new demoentity (null, "Chen Xuqin"));        Find Control RV = (Recyclerview) Findviewbyid (R.ID.RV);        Create a linear layout manager and set Linearlayoutmanager LayoutManager = new Linearlayoutmanager (this);        Layoutmanager.setorientation (linearlayoutmanager.vertical);        Rv.setlayoutmanager (LayoutManager);            commonrecyclerviewadapter<demoentity> adapter = new Commonrecyclerviewadapter<demoentity> (this, data) { @OVerride public void Convert (Commonrecyclerviewholder h, demoentity entity, int position) {int I                Temviewtype = Getitemviewtype (position);                if (Itemviewtype = = 1) {H.settext (R.id.tv_tag, Entity.gettag ());                } else {H.settext (r.id.tv_name, Entity.getname ());                }}//Returns the ID of the item layout @Override public int getlayoutviewid (int viewtype) {                if (ViewType = = 1) {return r.layout.tag;                } else {return r.layout.item; }}//The default is to return 0, so you can define a return of 1 to use tag,2 to represent the item,//The value returned here will appear in the Getlayoutviewid method @Over Ride public int getitemtype (int position) {//Returns the type of view based on the attributes in the Entity object demoentity dem                Oentity = Data.get (position); if (demoentity.gettag () = null) {//if it is tag, it should return 11;                } else {return 2;        }            }        };        Set adapter Rv.setadapter (adapter); Adapter.setonrecyclerviewitemclicklistener (New Commonrecyclerviewadapter.onrecyclerviewitemclicklistener () {@O Verride public void Onitemclick (View v, int position) {Toast.maketext (Mainactivity.this, "you clicked the            "+ Position +" item ", Toast.length_short). Show ();    }        }); }}

We see a Getitemtype method, which is used to return the logo of the ViewItem at the time of the subscript position, which can be defined by yourself, with 1 representing the name tag,2.

Then our Getlayoutviewid method is no longer simple to return to the same layout, it is necessary to return the corresponding XML ID according to the identity just

Similarly, in the Convert method, you also have to judge the control in the item to assign the value! The code is not difficult, bloggers have made comments

See effect


The number of data is less than sliding, you can make more of your own data.

For multi-layout item Click events, sometimes we need to take the name of the item's click Effect on the line, so adapter also provides the corresponding method

public void Setonrecyclerviewitemclicklistener (Onrecyclerviewitemclicklistener onrecyclerviewitemclicklistener, Int... Itemtypes)

Adapter.setonrecyclerviewitemclicklistener (New Commonrecyclerviewadapter.onrecyclerviewitemclicklistener () {        @Override public        void Onitemclick (View v, int position) {             Toast.maketext (multilayoutactivity.this, " You clicked on the "+ Position +" item ", Toast.length_short). Show ();        }, 2);

Be careful to see, set the listener last I followed a 2, then this 2 is what use? Remember the multi-layout above, our 2 represents the display name of item, so here's 2 refers to the Click event only for the display name of the item function, and this 2 is yourself on the above custom, so learn to work around

look at the effect!


Can see me anyway i click on the blue letter, here does not work, this design blogger feel quite 6, you say?

Demo to listen for click events on item Internal controlsFirst we add a button to the item in the display name
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent ">    <textview        android:id= "@+id/tv_name"        android:layout_width= "wrap_content"        android:layout_height= "wrap_content "        android:layout_centervertical=" true "        android:layout_marginleft=" 16DP "        android:text=" name "        Android:textsize= "16DP"/>    <!--Add a new button to the right of the text--    <button        android:id= "@+id/bt"        Android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_ Centervertical= "true"        android:layout_torightof= "@+id/tv_name"        android:text= "point Me"/></ Relativelayout>

A button is added.

And then, we're doing the activity to listen to the button in this item! The method is:

public void Setonviewinitemclicklistener (Onviewinitemclicklistener onviewinitemclicklistener, int ... viewIdsInItem)
Viewidsinitem is an array of shapes, the ID of the control in the item you want to listen to

Usage:

Add Item in the button control listener adapter.setonviewinitemclicklistener (new Commonrecyclerviewadapter.onviewinitemclicklistener () {        @Override public        void Onviewinitemclick (View v, int position) {            demoentity demoentity = data.get (position) ;            Toast.maketext (Multilayoutactivity.this, "You clicked on the first" + position + "Item,name =" + Demoentity.getname (), Toast.length_short ). Show ();        }}, R.ID.BT);

To be able to slide, the data I fake a little more

        Data.add (New Demoentity ("A", null));        Data.add (new demoentity (NULL, "A-Da"));        Data.add (new demoentity (null, "Auntie 1"));        Data.add (new demoentity (null, "Auntie 2"));        Data.add (new demoentity (null, "Auntie 3"));        Data.add (new demoentity (null, "Auntie 4"));        Data.add (New Demoentity ("C", null));        Data.add (new demoentity (null, "Chen Xu Gold 1"));        Data.add (new demoentity (null, "Chen Xu Gold 2"));        Data.add (new demoentity (null, "Chen Xu Gold 3"));        Data.add (new demoentity (null, "Chen Xuqin 4"));
Effect

You can see that the button in item is clicked successfully! and the corresponding name is displayed and clicking on item is a bit of an area

Demo Add header tryHeader XML
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android: background= "#FF0000" >    <relativelayout        android:layout_width= "match_parent"        android:layout_ height= "Wrap_content" >        <textview            android:layout_width= "wrap_content"            android:layout_height= " Wrap_content "            android:layout_centerinparent=" true "            android:text=" I am the head "            android:textcolor=" # FFFFFF "            android:textsize=" 40DP "/>    </RelativeLayout></RelativeLayout>
Then we add a head

Adapter.addheaderview (View.inflate (this, r.layout.header, null));

effect
Demo and Universal adapter source code DownloadHttps://github.com/xiaojinzi123/android-demos/tree/master/RecyclerViewDemo

Advanced use of the Recyclerview universal adapter

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.