Android CardView Using Kotlin With Example

In this article, we will learn about android CardView using Kotlin. We will go through various example that demonstrates how to use different attributes of CardView. For example,

In this article, we will get answer to questions like –

  • What is CardView?
  • Why should we consider CardView while designing ui for any app?
  • What are possibilities using CardView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin Android CardView Using Kotlin With Example

Getting Started

We can define android CardView widget as below –

CardView is subclass of FrameLayout with a rounded corner background and shadow. We can use it any project when we need to have card based user interface.

Now, how do we use CardView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as CardView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android CardView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using CardView in Kotlin

Follow steps below to use CardView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">CardView</string>
        <string name="orchid">Orchid</string>
        <string name="flower_image_description">Flower Image Description</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f0f0"
        tools:context=".MainActivity">
    
        <androidx.cardview.widget.CardView
            android:id="@+id/cardView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <TextView
                android:id="@+id/name1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="15dp"
                android:text="Card 1" />
    
        </androidx.cardview.widget.CardView>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Notice that we are using only textView inside CardView.

  • Now, we will access CardView in Kotlin file, MainActivity.kt, and perform some operation on it. So, open MainActivity.kt and add below code in it –

    package com.tutorialwing.cardview
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.cardview.databinding.ActivityMainSecondBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainSecondBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainSecondBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    	}
    }
    

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android CardView Using Kotlin With Example

Set Click Listener in CardView

Follow steps below to set click listener on cardView –

  1. Add below line in CardView –
    android:foreground="?android:attr/selectableItemBackground"
    
  2. Now, create a method, setupCardView, in MainActivity.kt file and add below code in it –
    private fun setupCardView() {
    	binding.cardView1.setOnClickListener {
    		Toast.makeText(baseContext, "Clicked on Card 1", Toast.LENGTH_SHORT).show()
    	}
    }
    

    Then, call this method from onCreate() method.

  3. Finally, code inside MainActivity.kt file is –
    package com.tutorialwing.cardview
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.cardview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupCardView()
    	}
    
    	private fun setupCardView() {
    		binding.cardView1.setOnClickListener {
    			Toast.makeText(baseContext, "Clicked on Card 1", Toast.LENGTH_SHORT).show()
    		}
    	}
    }
    
  4. Now, run application. We will get output as below –
    Tutorialwing Kotlin Android CardView Using Kotlin With Example

Design another UI with imageView, textView and CardView

Let’s design another ui that contains ImageView, TextView and CardView. Follow below steps –

  1. Create a new file, activity_main_second.xml, in res/layout folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f0f0"
        tools:context=".MainActivity">
    
        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="?android:attr/selectableItemBackground"
                tools:context=".MainActivity">
    
                <ImageView
                    android:id="@+id/image"
                    android:layout_width="150dp"
                    android:layout_height="200dp"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/flower_image_description"
                    android:src="@drawable/orchid"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />
    
                <TextView
                    android:id="@+id/name"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:padding="5dp"
                    android:text="@string/orchid"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/image" />
    
            </androidx.constraintlayout.widget.ConstraintLayout>
    
        </androidx.cardview.widget.CardView>
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  2. Now, open MainActivity.kt file. Then, add below code in it –
    package com.tutorialwing.cardview
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.cardview.databinding.ActivityMainSecondBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainSecondBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainSecondBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    	}
    }
    

    Here, we have changed ActivityMainBinding to ActivityMainSecondBinding.

  3. Now, run application. We will get output as below –
    Tutorialwing Kotlin Android CardView Using Kotlin With Example

Different Attributes of CardView in XML

Now, we will see how to use different attributes of Android CardView using Kotlin to customise it –

Set Id of CardView

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of CardView using android:id attribute like below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        />

Here, we have set id of CardView as cardView_ID using android:id=”” attribute. So, if we need to reference this CardView, we need to use this id – cardView_ID.

Set Width of CardView

We use android:layout_width=”” attribute to set width of CardView.
We can do it as below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of CardView

We use android:layout_height=”” attribute to set height of CardView.
We can do it as below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of CardView

We use android:padding=”” attribute to set padding of CardView.
We can do it as below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in CardView using android:padding=”” attribute.

Set Margin of CardView

We use android:layout_margin=”” attribute to set margin of CardView.
We can do it as below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in CardView using android:layout_margin=”” attribute.

Set Background of CardView

We use android:background=”” attribute to set background of CardView.
We can do it as below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in CardView using android:background=”” attribute.

Set Visibility of CardView

We use android:visibility=”” attribute to set visibility of CardView.
We can do it as below –

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of CardView using android:visibility=”” attribute. Visibility can be of three types – gone, visible and invisible

Till now, we have see how to use android CardView using Kotlin. We have also gone through different attributes of CardView to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android CardView Widget

Below are the various attributes that are used to customise android CardView Widget. However, you can check the complete list of attributes of CardView in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of android CardView inherited from viewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Defines whether to run layout transition when there is any change in layout
2 android:animationCache Defines whether to create drawing cache for children by layout animation
3 android:clipToPadding Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero
4 android:layoutAnimation Defines the layout animation to be used when the viewGroup is laid out for the first time
5 android:layoutMode Specifies the layout mode of the viewGroup

Some of the popular attributes of android CardView inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines alpha to the view
2 android:background Defines drawable to the background
3 android:backgroundTint Defines tint to apply to the background
4 android:clickable Defines whether the view is clickable or not
5 android:elevation Defines elevation of the view
6 android:focusable Defines whether this view can take focus or not
7 android:id Defines id of the view
8 android:visibility Defines the visibility(VISIBLE, INVISIBLE, GONE) of the view

We have seen different attributes of CardView and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is CardView, how can we use android CardView using Kotlin ? etc. We also went through different attributes of android CardView.

Leave a Reply

We are actively looking for Paid Content Writer. Email us at tutorialwing@gmail.com if you are interested.