Friday 9 October 2015

Android CardView Example

Android 5.0 (Lollipop), Google introduced two new Widgets: RecyclerView and CardView. The RecyclerView is a more advanced and more flexible version of the ListView. This new component is a big step because the ListView is one of the most used UI widgets. The CardView widget, on the other hand, is a new component that does not "upgrade" an existing component.



Before starting off don’t forget to include these dependencies in your app gradle.

build.gradle

dependencies {

    compile 'com.android.support:appcompat-v7:23.0.0'

    compile 'com.android.support:cardview-v7:23.0.0'

    compile 'com.android.support:recyclerview-v7:23.0.0'

}


Next please a look at activity layout, which shows the RecyclerView:

activity_main.xml

<?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=".CardViewActivity">

<android.support.v7.widget.RecyclerView      
android:id="@+id/my_recycler_view"      
android:layout_width="match_parent"      
android:layout_height="match_parent"      
android:scrollbars="vertical"/>

</RelativeLayout>



In this Android CardView Example, we will use this object for supplying the data to adapter:
DataObject.java

package com.example.cardview;


public class DataObject {
    private String mText1;
    private String mText2;

    DataObject (String text1, String text2){
        mText1 = text1;
        mText2 = text2;
    }

    public String getmText1() {
        return mText1;
    }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) {
        this.mText2 = mText2;
    }
}


 Lets have a look at the card_view_row.xml

 card_view_row.xml

 <?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.support.v7.widget.CardView      
android:id="@+id/card_view"      
android:focusable="true"      
android:clickable="true"      
android:foreground="?android:attr/selectableItemBackground"      
android:layout_width="fill_parent"      
android:layout_height="100dp"      
android:layout_gravity="center"      
android:layout_margin="5dp">

<RelativeLayout          
android:layout_width="fill_parent"          
android:layout_height="fill_parent">

<TextView              
android:id="@+id/textView"              
android:layout_width="wrap_content"              
android:layout_height="wrap_content"              
android:layout_alignParentTop="true"              
android:textStyle="bold" />

<TextView              
android:id="@+id/textView2"              
android:layout_width="wrap_content"              
android:layout_height="wrap_content"              
android:layout_below="@+id/textView"              
android:layout_marginTop="10dp" />

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


The activity below shows the CardView list:

MainActivity.java

package com.example.cardview;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);
    }
    @Override    protected void onResume() {
        super.onResume();
        ((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
                .MyClickListener() {
            @Override            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
                Toast.makeText(MainActivity.this,"clicked on item:"+position,Toast.LENGTH_SHORT).show();
            }
        });
    }

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();
        for (int index = 0; index < 20; index++) {
            DataObject obj = new DataObject("Heading Text " + index,
                    "Sub Text " + index);
            results.add(index, obj);
        }
        return results;
    }
}


Next lets have a look at the main class where RecyclerView adapter is defined. This class shows how to include an Android CardView widget in a RecyclerView:

MyRecyclerViewAdapter.java

package com.example.cardview;


import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.ArrayList;


public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View
            .OnClickListener {
        TextView label;
        TextView dateTime;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            dateTime = (TextView) itemView.findViewById(R.id.textView2);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.label.setText(mDataset.get(position).getmText1());
        holder.dateTime.setText(mDataset.get(position).getmText2());
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

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

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}


This would give an output screen with CardViews like these:



No comments:

Post a Comment