Skip to main content

Recycler View and Card View(Material Design) 

- Android Tutorial

RecyclerView and CardView are major element introduced in Material Design. RecyclerView is a flexible view for providing a limited window into a large data set.Using CardView you can represent the information in a card manner with a drop shadow (elevation) and corner radius which looks consistent across the platform. CardView extends the FrameLayout and it is supported way back to Android 2.x.

You can achieve good looking UI when CardView is combined with RecyclerView. 

How to Add RecyclerView & CardView?

Open build.gradle located under your app module and add below dependencies. After adding the dependencies, goto Build ⇒ Rebuild Project to download required libraries or Sync the project.

build.gradle
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    // RecyclerView
    compile 'com.android.support:recyclerview-v7:23.3.+'
    // CardView
    compile 'com.android.support:cardview-v7:23.3.+'
}


CardView is used to display single album item. RecyclerView is used to display the albums in grid manner. 
Glide is used to display the album cover images.

Look out an example which shows how to use the RecyclerView and CareView. This example is to display the images like music album.

Now let’s see this in action by creating a new project.

1. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Empty Activity and proceed.

2. Add some images to your projects res folder. This res folder contains few album covers and icons  required for this project.

3. Add required strings, colors and dimen resources to strings.xmlcolors.xml and dimens.xml files.

4. Open build.gradle and add CardViewRecyclerView and Glide dependencies. 
     RecyclerView is used to display the albums in grid manner. 
     CardView is used to display single album item. 
     Glide is used to display the album cover images.


build.gradle
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'

    // RecyclerView
    compile 'com.android.support:recyclerview-v7:23.3.+'
    // CardView
    compile 'com.android.support:cardview-v7:23.3.+'
    // Glide
    compile 'com.github.bumptech.glide:glide:3.7.0'
}

5. Open the activity_main.xml and replace with the following

<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"    
android:paddingBottom="@dimen/activity_vertical_margin"    
android:paddingLeft="@dimen/activity_horizontal_margin"    
android:paddingRight="@dimen/activity_horizontal_margin"    
android:paddingTop="@dimen/activity_vertical_margin"    
tools:context="com.mrbrown.recyclerview_cardview_sample.MainActivity">

    <FrameLayout        
         android:id="@+id/idFrame"        
         android:layout_width="match_parent"        
         android:layout_height="wrap_content">
        <ImageView            
             android:id="@+id/idCoverImg"            
             android:layout_width="match_parent"            
             android:layout_height="wrap_content"            
             android:layout_marginBottom="5dp"/>

        <TextView            
             android:layout_width="match_parent"            
             android:layout_height="wrap_content"            
             android:gravity="center"            
             android:layout_gravity="center"            
             android:fontFamily="serif"            
             android:textStyle="italic|bold"            
             android:textColor="@color/colorText"            
             android:textSize="40sp"            
             android:text="Top Album"/>
    </FrameLayout>

    <android.support.v7.widget.RecyclerView        
           android:id="@+id/idRecycler"        
           android:layout_below="@+id/idFrame"       
           android:layout_width="match_parent"        
           android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>



The FrameLayout used in the above xml will bring the view as
RecyclerView widget is added below the FrameLayout. 
This is the way to add the RecyclerView in our UI design.
6. Now create the new xml file to implement CardView, here uses as card_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="1dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/card_view">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageViewandroid:id="@+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="@dimen/album_cover_height"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/thumbnail" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
The CardView contain two items (ImageView & TextView). UI looks as below

7. Now work on java class, Open the MainActivity.java
Modify the class as below
public class MainActivity extends AppCompatActivity {
    private ImageView imgCover;
    private static RecyclerView recyclerView;
    private RecyclerView.LayoutManager m_LayoutManager;

    private ArrayList<Integer> timeNames;
    CustomAdapter customAdapter;

    @Override    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgCover = (ImageView) findViewById(R.id.idCoverImg);
        Glide.with(MainActivity.this)
                .load(R.drawable.cover)
                .into(imgCover);

        recyclerView = (RecyclerView)findViewById(R.id.idRecycler);
        recyclerView.setHasFixedSize(true);
        m_LayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(m_LayoutManager);

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,
StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //adding_images_from_drawable_to_arrayList
timeNames = new ArrayList<Integer>();
        timeNames.add(R.drawable.album1);
        timeNames.add(R.drawable.album2);
        timeNames.add(R.drawable.album3);
        timeNames.add(R.drawable.album4);
        timeNames.add(R.drawable.album5);
        timeNames.add(R.drawable.album6);
        timeNames.add(R.drawable.album7);
        timeNames.add(R.drawable.album8);
        timeNames.add(R.drawable.album9);
        timeNames.add(R.drawable.album10);
        timeNames.add(R.drawable.album11);

        //passing_arraylist&views        if(timeNames.size()>0){
            customAdapter = new CustomAdapter(MainActivity.this, 
timeNames, recyclerView);
//adapter has set to the recyclerView
            recyclerView.setAdapter(customAdapter);
        }

    }
}

In this class the green highlighted lines are the essential to use RecyclerView.
The yellow highlighted are to make the style to RecyclerView. By default a 
column has only one Item,but here we declared as 2 in vertical, so two item 
will set in a column as below
8. Now set an adapter class to set an items using CardView
Create a class CustomAdapter.java
Modify the class as below

public class CustomAdapter extends RecyclerView.Adapter{
RecyclerView mrecyclerview;
static Context context;
private ArrayList<Integer> Items = new ArrayList<Integer>();
public CustomAdapter(MainActivity context, ArrayList<Integer> arraySend,
RecyclerView recyclerView) {
this.context = context;
mrecyclerview = recyclerView;
Items = arraySend;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
RecyclerView.ViewHolder vh;
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, null);
vh = new ViewHolder(itemLayoutView);
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
final Integer tempMap = Items.get(position);
Glide.with(context)
.load(tempMap)
.into(((ViewHolder) holder).imgUrl);
}catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return Items.size();
}
private class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtConten;
ImageView imgUrl;
CardView cardview;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
cardview = (CardView) itemLayoutView.findViewById(R.id.card_view);
imgUrl = (ImageView) itemLayoutView.findViewById(R.id.thumbnail);
txtConten = (TextView) itemLayoutView.findViewById(R.id.title);
}
}
}

Final Output is as


____________________________________________________________
Source code for this RecyclerView&CardView.zip

Happy Coding...

Comments

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...