CheckedTextView is an extension of TextView in Android that includes a checkmark, making it function like a checkbox. It is commonly used in list views where items can be selected or toggled between checked and unchecked states. Users can tap the text to change its checked status, and the checkmark updates accordingly.
In this article, we will be discussing how to make a CheckedTextView dynamically or programmatically.
Steps of Implementation
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Modify the activity_main.xml file
Now, we need to modify our layout. For doing so : Go to app > res > layout > activity_main.xml and paste the following code.
activity_main.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="match_parent"
android:id="@+id/main"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
Step 3: Use CheckedTextView Code in MainActivity.kt file
The final step is to code our CheckedTextView. Navigate to app > src > main > java > {package-name} > MainActivity.kt.
MainActivity.kt:
package org.geeksforgeeks.demo
import android.os.Bundle
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val layout: LinearLayout = findViewById(R.id.main)
val checkedTextView = CheckedTextView(this)
checkedTextView.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
checkedTextView.text = "CheckedTextViewInKotlin"
//initially the checkbox in unchecked
checkedTextView.isChecked = false
checkedTextView.setCheckMarkDrawable(android.R.drawable.checkbox_off_background)
//Onclick event for checkbox
checkedTextView.setOnClickListener {
checkedTextView.isChecked = !checkedTextView.isChecked
checkedTextView.setCheckMarkDrawable(
if (checkedTextView.isChecked)
android.R.drawable.checkbox_on_background
else
android.R.drawable.checkbox_off_background
)
val msg = if (checkedTextView.isChecked)
"View is: checked"
else
"View is: unchecked"
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
}
// Add Checkbox to RelativeLayout
layout.addView(checkedTextView)
}
}