ANDROID L--recyclerview,cardview Import and use (Demo)

Source: Internet
Author: User

Reprint Please indicate this article from Big Corn's blog (http://blog.csdn.net/a396901990 ), thank you for your support!


Brief introduction:


This article is a supplement to the ANDROID l--material design (UI control) or an application example, if you have time to suggest a little glance at the previous article.


This article mainly introduces the new addition of Android L two UI control Recyclerview,cardview Import and use.

Recyclerview is an upgraded version of the ListView

CardView is a card-view component provided by Google


This example is a small example of using Recyclerview to show multiple CardView, first look at:






Import Recyclerview,cardview


because Recyclerview , CardView is placed in the Support library V7 package, so we want to use it must have to guide the package.

Here's how the two packages are imported in Eclipse and Android Studio .



Eclipse:


First step: download/update Android support Libraries with SDK Manager (5.0 version up to 21)



Step Two: import CardView and Recyclerview items (both in support V7)

1. Click Import in Eclipse, importing the Android project

2. Import CardView and Recycleview, path is your SDK Path\extras\android\support\v7\cardview (Recycleview is recyclerview in same directory)

3. When importing, remember to copy the project to local and suggest renaming, so as to facilitate later management such as:



Step three: set up the library

1. Set the two projects to the library

2. The introduction of these two libraries in the main project for example:



These two packages can be imported in these three steps.



Android Studio


Android Stuido is much simpler than eclipse:

The first step:

First make sure you've upgraded your Android support libraries to the latest.


Step Two:

Open the Build.gradle file in your project and add the following code to the dependencies.

dependencies {    compile ' com.android.support:recyclerview-v7:21.+ '    compile ' com.android.support: Cardview-v7:21.+ '}


Step Three:

Re-build the project.


when the build is complete, you'll see that these two packages are already imported.





Code Description:


Theme:


First of all, the theme of this black keynote is the use of the Material.Dark.ActionBar style.


Setup method: Modify the Styles.xml file under the Values-v21 folder:

<resources>    <style name= "Apptheme" parent= "Android:ThemeOverlay.Material.Dark.ActionBar" >    </style></resources>


Layout file:

Recycler_view.xml (Recyclerview layout file):

<?xml version= "1.0" encoding= "Utf-8"? ><framelayout 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= ". MyActivity ">    <android.support.v7.widget.recyclerview        android:id=" @+id/list "        android:layout_ Width= "Match_parent"        android:layout_height= "match_parent"        tools:context= ". MyActivity "/></framelayout>
the Recyclerview control is included in the Framelayout



Card_view.xml (cardview layout file ):

<android.support.v7.widget.cardview xmlns:android= "Http://schemas.android.com/apk/res/android" Xmlns:card_ view= "Http://schemas.android.com/apk/res-auto" android:layout_width= "match_parent" android:layout_height= "Match_ Parent "android:layout_margin=" 5DP "android:orientation=" horizontal "card_view:cardbackgroundcolor=" @color/cardvi Ew_dark_background "card_view:cardcornerradius=" 5DP "> <relativelayout android:layout_width=" match_pare NT "android:layout_height=" 100DP "android:padding=" 5DP "> <imageview android:id=" @+i D/pic "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:l Ayout_centerinparent= "true" android:scaletype= "Centercrop"/> <textview Android:clickab Le= "true" android:id= "@+id/name" android:layout_width= "Match_parent" Android:layout_heigh t= "Match_parent" Android:laYout_marginbottom= "10DP" android:layout_marginright= "10DP" android:gravity= "Right|bottom" Android:textcolor= "@android: Color/white" android:textsize= "24sp"/> </relativelayout></android. Support.v7.widget.cardview>

The CardView view contains a imageview and a textview that display pictures and text messages separately

The only thing you need to introduce is using the following two properties in the layout file:

Card_view:cardbackgroundcolor= "@color/cardview_dark_background"    card_view:cardcornerradius= "5DP"
Their role is to set the CardView background color and the perimeter fillet size (note to use the Card_view namespace)



Code:


Actor Class (model class for encapsulating data):

public class actor{    String name;    String Picname;    Public Actor (string name, String picname)    {        this.name = name;        This.picname = Picname;    }    public int Getimageresourceid (context context)    {        try        {            return context.getresources (). Getidentifier (This.picname, "drawable", Context.getpackagename ());        }        catch (Exception e)        {            e.printstacktrace ();            return-1;}}}    
encapsulates the actor's name and picture name, and theGetimageresourceid () method works by finding system resources based on the image

MyActivity (Program master control activity)

public class MyActivity extends activity{private Recyclerview mrecyclerview;    Private Myadapter Myadapter;    Private list<actor> actors = new arraylist<actor> ();    Private string[] names = {"Athena Chu", "Cecilia Cheung", "Zhang Min", "Gong Li", "Huangshengyi", "Zhao Wei", "Karen Mok", "such as Flowers"};    Private string[] Pics = {"P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.recycler_view);        Actors.add (New Actor ("Athena Chu", "P1"));        Getactionbar (). Settitle ("The Star girl we chased in those years");        Get Recyclerview Mrecyclerview = (recyclerview) Findviewbyid (r.id.list);        Set Linearlayoutmanager Mrecyclerview.setlayoutmanager (new Linearlayoutmanager (this));        Set Itemanimator mrecyclerview.setitemanimator (New Defaultitemanimator ());        Sets the fixed size mrecyclerview.sethasfixedsize (true); Initialize the custom adapter Myadapter = new Myadapter (This, aCtors);    Set Adapter Mrecyclerview.setadapter (Myadapter) for Mrecyclerview;        @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.menu, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {//When point When you click the Add button on Actionbar, add a new data to adapter and notify the Refresh case R.id.action_add:if (Myadapter.getitemcount ()! = NA                    Mes.length) {Actors.add (New Actor (Names[myadapter.getitemcount (), Pics[myadapter.getitemcount ()]));                    Mrecyclerview.scrolltoposition (Myadapter.getitemcount ()-1);                Myadapter.notifydatasetchanged ();            } return true; When you click the Delete button on Actionbar, remove the last data to adapter and notify the Refresh case R.id.action_remove:if (Myadapter.getitemcoun                    T () = 0) {actors.remove (Myadapter.getitemcount ()-1); MReCyclerview.scrolltoposition (Myadapter.getitemcount ()-1);                Myadapter.notifydatasetchanged ();        } return true;    } return super.onoptionsitemselected (item); }}


Myadapter (Custom adapter Class)

public class Myadapter extends recyclerview.adapter<myadapter.viewholder>{private list<actor> actors;    Private Context Mcontext;        Public Myadapter (context context, list<actor> actors) {This.mcontext = context;    This.actors = actors;        } @Override Public Viewholder oncreateviewholder (viewgroup viewgroup, int i) {//Set layout file for Viewholder        View v = layoutinflater.from (Viewgroup.getcontext ()). Inflate (R.layout.card_view, ViewGroup, false);    return new Viewholder (v);  } @Override public void Onbindviewholder (Viewholder viewholder, int i) {//Set element to Viewholder Actor        p = actors.get (i);        ViewHolder.mTextView.setText (P.name);    ViewHolder.mImageView.setImageDrawable (Mcontext.getdrawable (P.getimageresourceid (Mcontext)));    } @Override public int getitemcount () {//Returns the total number of data return actors = = null? 0:actors.size (); }//overridden custom Viewholder public static CLASS Viewholder extends Recyclerview.viewholder {public TextView mtextview;        Public ImageView Mimageview;            Public Viewholder (View v) {super (V);            Mtextview = (TextView) V.findviewbyid (r.id.name);        Mimageview = (ImageView) V.findviewbyid (r.id.pic); }    }}



All the code has been introduced, can be summarized as the following two points:


Recyclerview:

Understood as the previous ListView, but need to set Linearlayoutmanager (currently not much information I'm a little confused later add) and Itemanimator ( animate each entry ) two new properties


Recyclerview.adapter:

The new adapter is understood as default and Viewholder based, except that the callback method is slightly different, but essentially the same.


Code: Https://github.com/a396901990/AndroidDemo



Written at the end:


A series of articles recently written in an Android l--material design.

Themes and layouts -- ANDROID l--material Design Details (themes and layouts)

views and Shadows- ANDROID l--material Design details (views and shadows)

UI Controls -- ANDROID l--material Design Details (UI controls)

Animation


This is only the last animated part. The original plan is to wait until the animation is finished writing their use of the demo, but the previous UI control feel not enough detail, so first write the UI control demo.

View shadow and animation using the demo and other last animated article after the end of the update, please look forward to ...




ANDROID L--recyclerview,cardview Import and use (Demo)

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.