Recyclerview inside Cardview

3.3k views Asked by At

i've been success create Recyclerview and Cardview. But now i need to create list data inside the Cardview, can i use Recyclerview inside Cardview ?

Please help me, how to implement the new Adapter for Recyclerview that i have made below.

This is my xml file for Cardview with Recyclerview inside it :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:padding="3dp">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cv">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/person_photo"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="16dp"
                android:contentDescription="@string/deskripsi"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/person_name"
                android:layout_toEndOf="@+id/person_photo"
                android:layout_alignParentTop="true"
                android:textSize="30sp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/person_age"
                android:layout_toEndOf="@+id/person_photo"
                android:layout_below="@+id/person_name"/>

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/rv"
                android:layout_below="@+id/person_photo" />

        </RelativeLayout> 
    </android.support.v7.widget.CardView> 
</LinearLayout>

and this is my adapter :

import java.util.List;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ImageView;
import android.support.v7.widget.CardView;
import io.hidayat.iocardview.Person;

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>{

    List<Person> persons;

    RVAdapter(List<Person> persons){
        this.persons = persons;
    }

    public static class PersonViewHolder extends RecyclerView.ViewHolder {      
        CardView cv;
        TextView personName;
        TextView personAge;
        ImageView personPhoto;

        PersonViewHolder(View itemView) {
            super(itemView);
            cv = (CardView)itemView.findViewById(R.id.cv);
            personName = (TextView)itemView.findViewById(R.id.person_name);
            personAge = (TextView)itemView.findViewById(R.id.person_age);
            personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
        }
    }

    @Override
    public int getItemCount() {

        return persons.size();
    }

    @Override
    public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {

        personViewHolder.personName.setText(persons.get(i).name);
        personViewHolder.personAge.setText(persons.get(i).age);
        personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
    }

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_list, viewGroup, false);
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {

        super.onAttachedToRecyclerView(recyclerView);
    }
}

Then i create new Adapter for the Recyclerview inside cardview :

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private ItemData[] itemsData;

    public MyAdapter(ItemData[] itemsData) {

        this.itemsData = itemsData;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){

        // create a new view
        View itemLayoutView = LayoutInflater.from(parent.getContext())
                               .inflate(R.layout.item_view, parent, false);

        // create ViewHolder        
        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {

        // - get data from your itemsData at this position
        // - replace the contents of the view with that itemsData         
        viewHolder.txtViewTitle.setText(itemsData[position].getTitle());
        viewHolder.imgViewIcon.setImageResource(itemsData[position].getImageUrl());
    }

    // inner class to hold a reference to each item of RecyclerView 
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView txtViewTitle;
        public ImageView imgViewIcon;

        public ViewHolder(View itemLayoutView) {

            super(itemLayoutView);
            txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
            imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
        }
    }


    // Return the size of your itemsData (invoked by the layout manager)
    @Override
    public int getItemCount() {

        return itemsData.length;
    }
}

this is the xml file for new Adapter :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp">

     <!-- icon -->
     <ImageView
         android:id="@+id/item_icon"
         android:layout_width="64dp"
         android:layout_height="64dp"
         android:layout_alignParentStart="true"
         android:layout_marginLeft="8dp"
         android:layout_marginRight="8dp"
         android:layout_marginTop="1dp"
         android:layout_marginBottom="1dp"
         android:contentDescription="@string/deskripsi"
         android:src="@drawable/ic_launcher"
     />

    <!-- title -->
    <TextView
         android:id="@+id/item_title"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_toEndOf="@+id/item_icon"
         android:layout_alignBaseline="@+id/item_icon"
         android:textColor="@android:color/darker_gray"
          android:layout_marginLeft="8dp"
         android:layout_marginRight="8dp"
         android:layout_marginTop="8dp"
         android:textSize="22sp" />

</RelativeLayout>

main_activity.java :

package io.hidayat.iocardview;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;

import io.hidayat.iocardview.Person;

public class MainActivity extends Activity {

    private List<Person> persons = initializeData();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        RecyclerView rv = (RecyclerView)findViewById(R.id.rv);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        rv.setLayoutManager(llm);

        RVAdapter adapter = new RVAdapter(persons);
        rv.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private List<Person> initializeData(){

        persons = new ArrayList<Person>();
        persons.add(new Person("Emma Wilson", "23 years old", R.drawable.ct_award));
        persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.ct_belanja));
        persons.add(new Person("Lillie Watts", "35 years old", R.drawable.ct_dipinjam));
        persons.add(new Person("Emma Wilson", "23 years old", R.drawable.ct_award));
        persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.ct_belanja));
        persons.add(new Person("Lillie Watts", "35 years old", R.drawable.ct_dipinjam));
        persons.add(new Person("Emma Wilson", "23 years old", R.drawable.ct_award));
        persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.ct_belanja));
        persons.add(new Person("Lillie Watts", "35 years old", R.drawable.ct_dipinjam));
        return persons;
    }
}
2

There are 2 answers

0
ItsJamez On

Using RecyclerView inside Cardview is very simple. In Android, CardView is another main element that can represent the information in a card manner with a drop shadow called elevation and corner radius which looks consistent across the platform.We can easily design good looking UI when we combined CardView with RecyclerView. A CardView is a ViewGroup that can be added in our Activity or Fragment using a layout XML file.

Basic CardView XML code In Android Studio:

`<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.CardView>

Add inside Gradle Scripts > build.gradle (Module: app) and inside dependencies

dependencies {
compile 'com.android.support:cardview-v7:23.0.1'
}

Read Full Article how to use Recyclerview inside Cardview with simple Example from http://abhiandroid.com/materialdesign/cardview

2
AudioBubble On

You don't need a Cardview adapter. So delete MyAdapter. Just use the RVAdapter as you do in the normal RecyclerView. For adding cardviews, to the recycler view, you just need to change the layout of recycler view items.Do something like this.

This is the adapter for recycler view

public class SpeakersListAdapter extends RecyclerView.Adapter<SpeakersListAdapter.ViewHolder> {
    List<Speaker> speakers;

    public SpeakersListAdapter(List<Speaker> speakers) {
        this.speakers = speakers;
    }

    @Override
    public SpeakersListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.speakers_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(SpeakersListAdapter.ViewHolder holder, int position) {

        Speaker current = speakers.get(position); //Arrayist of speakers

        holder.designation.setText(current.getPosition());
        holder.name.setText(current.getName());
        holder.bio.setText(current.getBio());
    }

    @Override
    public int getItemCount() {
        return speakers.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView name;

        TextView designation;

        TextView bio;

        public ViewHolder(View itemView) {
            super(itemView);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);

            name = (TextView) itemView.findViewById(R.id.speaker_name);
            bio = (TextView) itemView.findViewById(R.id.speaker_bio);
            designation = (TextView) itemView.findViewById(R.id.speaker_designation);
        }
    }
    }

This is layout of what a recycler view item looks like, So we add cardView here (speakers_item.xml)

<android.support.v7.widget.CardView
    android:id="@+id/card_tracks"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:layout_gravity="center"
    android:layout_margin="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/main_ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical">

            <ImageView
                android:id="@+id/speaker_image"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_margin="10dp"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:src="@drawable/default_user"/>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView
                    android:id="@+id/speaker_name"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="0.5"
                    android:gravity="center_vertical"
                    android:text="placeholder_speaker_name"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000000"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/speaker_designation"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="0.5"
                    android:gravity="top"
                    android:text="placeholder_speaker_designation"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="#000000"
                    android:textStyle="bold"/>

            </LinearLayout>

        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/speaker_bio"
                android:layout_width="326dp"
                android:layout_height="64dp"
                android:layout_margin="10dp"
                android:text="placeholder_speaker_bio"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="#000000"/>
        </RelativeLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

Now the main activity layout that has the Recycler View. (list_speakers.xml)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_speakers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="7dp"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

Now I have added a fragment where I inflate these layouts

public class SpeakerFragment extends Fragment {

    RecyclerView speakersRecyclerView;
    SpeakersListAdapter speakersListAdapter;
    DbSingleton dbSingleton = DbSingleton.getInstance();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_speakers, container, false);
        speakersRecyclerView = (RecyclerView) view.findViewById(R.id.rv_speakers);
        speakersListAdapter = new SpeakersListAdapter(dbSingleton.getSpeakerList());
        speakersRecyclerView.setAdapter(speakersListAdapter);
        speakersRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return view;
    }
}

Give a vote up if you like the answer !! Cheers !