Android l -- RecyclerView, CardView import and use (Demo), cardviewandroid

Source: Internet
Author: User

Android l -- RecyclerView, CardView import and use (Demo), cardviewandroid

Reprinted please indicate this article from the blog of the big glutinous rice ( Thank you for your support!


This article isAndroid l -- Material Design (UI control)Is a supplement or application instance. If you have time, you are advised to take a look at the previous article.

This article mainly introduces two newly added UI controls for Android L.RecyclerView,CardView.

RecyclerView is an upgraded version of ListView.

CardView is a card view component provided by Google.

This example uses RecyclerView to show a small example of multiple CardView S. Let's take a look at the following:

Import RecyclerView and CardView

Because RecyclerView, CardView is placed in the support library v7 package, you must export the package if you want to use it.

The following describesEclipseAndAndroid StudioTo import the two packages.


Step 1:Download/update Android Support Libraries through SDK manager (Version 5.0 is 21)

Step 2:Import CardView and RecyclerView projects (both in support v7)

1. Click Import in Eclipse to Import the Android Project

2. Import CardView and RecycleView. The path is your sdk path \ extras \ android \ support \ v7 \ cardview (RecycleView is recyclerview under the same directory)

3. During import, remember to copy the project to your local computer and rename it. This will facilitate future management, for example:

Step 3:Set Library

1. Set two projects to Library

2. introduce these two libraries in the main project, for example:

You can import the two packages in these three steps.

Android Studio

Compared with Eclipse, Android Stuido is much simpler:

Step 1:

First, make sure that the Android Support Libraries has been upgraded to the latest version.

Step 2:

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

dependencies {    compile ''    compile ''}

Step 3:

Re-Build the project.

After the Build is complete, you will find that these two packages have already been imported.

Code introduction:


First, the subject of this black tone uses the Material. Dark. ActionBar style.

Setting Method: Modify the styles. xml file in 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=""    xmlns:tools=""    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MyActivity">    <        android:id="@+id/list"        android:layout_width="match_parent"        android:layout_height="match_parent"        tools:context=".MyActivity" /></FrameLayout>
FrameLayout contains the RecyclerView control.

Card_view.xml (CardView layout file ):

< xmlns:android=""    xmlns:card_view=""    android:layout_width="match_parent"    android:layout_height="match_parent"    android:layout_margin="5dp"    android:orientation="horizontal"    card_view:cardBackgroundColor="@color/cardview_dark_background"    card_view:cardCornerRadius="5dp" >    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="100dp"        android:padding="5dp" >        <ImageView            android:id="@+id/pic"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_centerInParent="true"            android:scaleType="centerCrop" />        <TextView            android:clickable="true"            android:id="@+id/name"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_marginBottom="10dp"            android:layout_marginRight="10dp"            android:gravity="right|bottom"            android:textColor="@android:color/white"            android:textSize="24sp" />    </RelativeLayout></>

The CardView view contains an ImageView and a TextView to display the image and text information respectively.

The only thing that needs to be introduced is to use the following two attributes in the layout file:

 card_view:cardBackgroundColor="@color/cardview_dark_background"    card_view:cardCornerRadius="5dp"
They respectively set the background color of CardView and the peripheral rounded corner size (note that the card_view namespace should be used)


Actor class (Model class that encapsulates data ):

public class Actor{    String name;    String picName;    public Actor(String name, String picName)    { = 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;        }    }}
It encapsulates the actor name and image name. The getImageResourceId () method is used to locate system resources based on the Image life.


Public class MyActivity extends Activity {private RecyclerView mRecyclerView; private MyAdapter myAdapter; private List <Actor> actors = new ArrayList <Actor> (); private String [] names = {"Zhu Yin ", "Cecilia Cheung", "Zhang Min", "Gong Li", "Huang shengyi", "Zhao Wei", "mo Wenwei", "Ru Hua"}; private String [] pics = {"p1 ", "p2", "p3", "p4", "p5", "p6", "p7", "p8" };@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (saved InstanceState); setContentView (R. layout. recycler_view); actors. add (new Actor ("Zhu Yin", "p1"); getActionBar (). setTitle ("star girls we chased in those years"); // get RecyclerView mRecyclerView = (RecyclerView) findViewById (R. id. list); // set LinearLayoutManager mRecyclerView. setLayoutManager (new LinearLayoutManager (this); // sets ItemAnimator mRecyclerView. setItemAnimator (new DefaultItemAnimator (); // set the fixed size of mRecyclerView. setHasFi XedSize (true); // initialize the custom adapter myAdapter = new MyAdapter (this, actors); // set the adapter mRecyclerView for mRecyclerView. setAdapter (myAdapter) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. menu, menu); return true ;}@ Override public boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {// when you click the Add button on the actionbar, add a new data to the adapter and notify the refresh case R. id. act Ion_add: if (myAdapter. getItemCount ()! = Names. 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 the actionbar, remove the last data from the adapter and notify the refresh case R. id. action_remove: if (myAdapter. getItemCount ()! = 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 the layout File View v = LayoutInflater for ViewHolder. from (viewGroup. getContext ()). inflate (R. la Yout. card_view, viewGroup, false); return new ViewHolder (v) ;}@ Override public void onBindViewHolder (ViewHolder viewHolder, int I) {// set the Actor p = actors for ViewHolder. get (I); viewHolder. mTextView. setText (p. name); viewHolder. mImageView. setImageDrawable (mContext. getDrawable (p. getImageResourceId (mContext);} @ Override public int getItemCount () {// total number of returned data return actors = null? 0: actors. size ();} // rewrite the 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 );}}}

After all the code is introduced, we can summarize the following two points:


It is understood as the previous ListView. However, you need to set two new attributes: LinearLayoutManager (I am not familiar with many materials now) and ItemAnimator (set operation animation for each entry ).

RecyclerView. Adapter:

It is understood that the default and new adapters Based on ViewHolder are slightly different, but the callback method is essentially the same.



I recently wrote a series of articles about ANDROID L-Material Design.

Themes and Layout--Android l-Material Design (subject and layout)

View and shadow-android l-Material Design (view and shadow)

UI control--Android l -- Material Design (UI control)


Currently, only the last animation part is missing. The original plan was to write their Demo after writing the animated articles. However, the previous UI control was not detailed enough, so I wrote the Demo of the UI control first.

View shadows and animations are updated after you finish the last animation, such as Demo...

I learned about Android and wrote a small demo of the View class, but I don't understand it.

This is the original statement in the API:


Public void setMinimumWidth (int minWidth)
Sets the minimum width of the view. It is not guaranteed the view will be able to achieve this minimum width (for example, if its parent layout constrains it with less available width ).

Parameter: minWidth-The minimum width the view will try to be.
Set the minimum width of the view. It is the minimum width that a view cannot guarantee to achieve this goal (for example, if its parent layout limits its available width ). The meaning of another method is similar.

When android calls the Baidu cloud storage api, the ak of the demo can be accessed normally, but the callback address error occurs when the ak is used.

The Baidu Developer Center has an SDK. Download it and check it out.

Related Article

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: 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.