Tutorial #93: Implement CardView in Android

Hello everyone!

Prior to Android 5.0 Lollipop, developers would use open source libraries in order to implement a Card based view in Android. However, the latest release of Android now provides a CardView widget to show information inside cards that have a consistent look across the platform. In general, CardView widgets can have shadows and rounded corners.

As mentioned on the developer’s page, in order to create a card with a shadow, one can use the card_view:cardElevation attribute. CardView uses real elevation and dynamic shadows on Android 5.0 (API level 21) and above and falls back to a programmatic shadow implementation on earlier versions. Through this tutorial, we will learn how to implement a CardView in Android.

Pre-requisites: Eclipse IDE, Android SDK 5.0

Step 1: Create Android project

Launch the Eclipse IDE and create a new Android application project called AndroidLollipopNewExamples with package name com.app.lollipop.test. Let the target SDK be Android 5.0 (API level 21)

Step 2: Create Card layout

Now, let’s create our card layout using XML. Create a new XML file called activity_cardview and add the following code!

activity_cardview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:gravity="center_horizontal"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_marginTop="20dp"
        android:layout_width="200dp"
        android:layout_height="100dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardBackgroundColor="#C92A2A">

        <TextView
            android:id="@+id/info_text_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/sample_text_header" />

        <ImageView
            android:id="@+id/info_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/sample_text_image"
            android:layout_gravity="center"
            android:layout_marginTop="2dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/info_text_footer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="80dp"
            android:text="@string/sample_text_footer" />
    </android.support.v7.widget.CardView>

</LinearLayout>

To set the corner radius in your layouts, use the card_view:cardCornerRadius attribute. To set the corner radius in your Java code, use the CardView.setRadius method. Finally, in order to set the background color of a card, use the card_view:cardBackgroundColor attribute.

strings.xml

<resources>
    <string name="app_name">AndroidLollipopNewExamples</string>
    <string name="sample_text_header">Sample card header</string>
    <string name="sample_text_footer">Sample card footer</string>
    <string name="sample_text_image">Sample image</string>
</resources>

Step 3: Create Activity class

Our Activity class called TestCardActivity would be as follows,

TestCardActivity.java

package com.app.lollipop.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class TestCardActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cardview);
	}	
}

No changes are to be made to the AndroidManifest.xml file. Run the application on an emulator and you should see the following output!

output

Reference: Creating Cards in Android

Implement RecyclerView in Android

Hello friends!

In one of my previous posts, I had talked about a new feature called Activity Transitions introduced in Android 5.0 Lollipop. In addition, Google has also introduced two new views namely RecyclerView and CardView. The RecyclerView widget is used primarily in applications that consists of data collections whose elements change at runtime. The change can occur either due to user action or network events.

As mentioned on the developer’s page, the RecyclerView class simplifies the display and handling of large data sets by providing,

  • Layout managers for positioning items.

  • Default animations for common item operations, such as removal or addition of items.

In order to recycle or reuse a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Through this post we will learn how to implement a RecyclerView in Android.

Pre-requisites: Eclipse IDE, Android SDK 5.0

We will be using our existing AndroidLollipopExamples project as mentioned in the previous post in order to implement the RecyclerView.

Step 1: Getting the support library

In order to use the RecyclerView one needs to download and install the latest version of the Android support library from the SDK Manager as seen below.

support_library

Once the support library is installed, navigate to the {ANDROID-SDK}\sdk\extras\android\support\v7\recyclerview directory and copy paste the .jar file present in the libs folder in your Android project. One can also import the same as a library project and add it as a reference to your existing Android project.

Step 2: Create layout for RecyclerView

Create a new XML file called activity_recycler_view.xml and write the following code.

activity_recycler_view.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="${relativePackage}.${activityClass}" >

    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Step 3: Create Adapter class

Next, we need to create an Adapter class that will bind the data to the View. Let’s call it MyAdapter. It will contain the following code.

MyAdapter.java

package com.app.android.lollipop;

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

@SuppressLint("InflateParams")
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

	private FruitModel[] fruitsData;

	public MyAdapter(FruitModel[] fruitsData) {
		this.fruitsData = fruitsData;

	}

	@Override
	public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

		//create view and viewholder
		View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fruit, null);
		ViewHolder viewHolder = new ViewHolder(itemLayoutView);
		return viewHolder;
	}

	// Replace the contents of a view 
	@Override
	public void onBindViewHolder(ViewHolder viewHolder, int position) {    
		viewHolder.txtViewTitle.setText(fruitsData[position].getFruitName());
	}

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

		public TextView txtViewTitle;

		public ViewHolder(View itemLayoutView) {
			super(itemLayoutView);	
			txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.fruit_name);
		}	
	}

	// Returns the size of the fruitsData
	@Override
	public int getItemCount() {
		return fruitsData.length;
	}
}

item_fruit.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="15dp">

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The layout that will be used for each item in the RecyclerView contains only one TextView at present. However, one can also add other views (eg. ImageView) if required.

Step 4: Create Activity class

The actual implementation of the RecyclerView happens in the Activity class. Here, we will get the reference to the view and populate the data required.

TestRecyclerViewActivity.java

package com.app.android.lollipop;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
 
public class TestRecyclerViewActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
         
        FruitModel fruitsData[] = { new FruitModel("Apple"),
                new FruitModel("Banana"),
                new FruitModel("Orange"),
                new FruitModel("Pineapple"),
                new FruitModel("Mango"),
                new FruitModel("Watermelon"),
                new FruitModel("Strawberry"),
                new FruitModel("Grapes"),
                new FruitModel("Jackfruit"),
                new FruitModel("Carrot"),
                new FruitModel("Fig")};
        
        //set layoutManger
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        MyAdapter mAdapter = new MyAdapter(fruitsData);
        //set adapter
        recyclerView.setAdapter(mAdapter);
        //set item animator to DefaultAnimator
        recyclerView.setItemAnimator(new DefaultItemAnimator());
 
    }
}

No changes are to be made to the AndroidManifest.xml file. Finally, make sure no errors are present. Run the application on an Android emulator and you should see the following output! 🙂

output_recycler_view

Next, we will look at implementing the CardView in Android.

Reference: Android RecyclerView

Activity Transitions using Android 5.0

Hello everyone!

Android 5.0 Lollipop is now officially launched by Google. The new version of Android brings in a lot more features allowing developers to create much better mobile applications. One of the key highlights of this new version includes Material Design. It is basically a comprehensive guide for visual, motion, and interaction design across platforms and devices.

Through material design, developers can also define custom animations. Android 5.0 introduces some default animations for buttons and activity transitions. Through this post, we will learn how to perform an Activity Transition in Android.

Pre-requisites: Eclipse IDE, Android SDK with Android 5.0 Lollipop

Step 1: Create Android project

Launch Eclipse IDE and create a new Android Application Project called AndroidLollipopExamples with package name com.app.android.lollipop. Choose the target SDK as Android 5.0 (API level 21). In case you don’t see the target API level 21 listed, you can download and install the same from the SDK Manager.

android_target_sdk

Step 2: Create Activity class

In order to perform a transition, we need to create two Activities. Let us name our activities as FirstActivity and SecondActivity respectively. The transition will take place while moving from the first to the second activity via an Intent. Our FirstActivity class would be as follows,

FirstActivity.java

package com.app.android.lollipop;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.transition.Explode;
import android.transition.Transition;
import android.view.Window;

@SuppressWarnings("unchecked")
public class FirstActivity extends Activity {

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
        //enable window content transition
		getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        //set the transition
		Transition ts = new Explode();  
		ts.setStartDelay(2000);
        //set the duration
		ts.setDuration(5000);
		getWindow().setEnterTransition(ts);
        //set an exit transition so it is activated when the current activity exits
		getWindow().setExitTransition(ts);
		setContentView(R.layout.activity_first);
		launchSecondActivity();
	}

	//this will call the second activity resulting in an exit transition
	@SuppressLint("NewApi")
	public void launchSecondActivity() {
		Intent intent = new Intent(this, SecondActivity.class);
		startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
	}	
}

activity_first.xml

<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="${relativePackage}.${activityClass}">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/first_activity" />

</RelativeLayout>

We then need to define a transition in our next Activity as well. Here’s how the SecondActivity class will finally look.

package com.app.android.lollipop;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.transition.Slide;
import android.transition.Transition;
import android.view.Window;

public class SecondActivity extends Activity {
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        //enable window content transition
		getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        //set the transition
		Transition ts = new Slide();  
		ts.setDuration(3000);
		getWindow().setEnterTransition(ts);
		getWindow().setExitTransition(ts);
		setContentView(R.layout.activity_second);
	}
}

activity_second.xml

<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="${relativePackage}.${activityClass}">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/second_activity" />

</RelativeLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidLollipopExamples</string>
    <string name="first_activity">First Activity</string>
    <string name="second_activity">Second Activity</string>    
</resources>

Note:

Make sure you have registered the SecondActivity within the application tag in the AndroidManifest.xml file as follows!

AndroidManifest.xml

....
 <activity
     android:name="com.app.android.lollipop.SecondActivity"
     android:label="@string/app_name" />
....

Finally, make sure no errors are present. Save all changes and run the application on an emulator running Android 5.0 and you should see the activity transition taking place! 🙂

Reference: Custom Animations in Android