CheckedTextView Example


A CheckedTextView is an extension of normal TextView that supports the checkable interface and displays it. It is similar to CheckBox, except that the TextView is towards left of CheckBox.

Here we will create a simple app which displays a CheckedTextView, and shows home as up button on ActionBar when it is checked.

Step 1: Create a new project with name ‘App Example’ and package name com.myexample.appcompat.checkedtextview. Fill the forms and click “Finish” button.

Step 2: In app level build.gradle add following dependencies:

dependencies {
	compile fileTree(dir: 'libs', include: ['*.jar'])
	compile 'com.android.support:appcompat-v7:27.0.2'
	compile 'com.android.support:design:27.0.2'
	compile 'com.android.support:support-v4:27.0.2'
}

Step 3: Open res -> layout -> xml (or) main.xml and add codes for displaying a CheckedTextView mainCheckedTextView. Here we specify checked state of CheckedTextView as false and specify it’s checkMark and text. We can also add image icon to the left of Text in this CheckedTextView.

<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=".MainActivity">

	<CheckedTextView
		android:id="@+id/mainCheckedTextView"
		android:layout_width="fill_parent"
		android:layout_height="50dp"
		android:checked="false"
		android:checkMark="?android:attr/listChoiceIndicatorMultiple"
		android:gravity="center_vertical"
		android:paddingLeft="15dp"
		android:textColor="#000"
		android:text="Show ActionBar HOME button" />
	
</RelativeLayout>

Step 4: Open app -> java -> package and open MainActivity.java. Add following code in it.

package com.myexample.appcompat.checkedtextview;

import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.support.v7.app.AppCompatActivity;
import android.widget.*;

public class MainActivity extends AppCompatActivity {
	// Declare CheckedTextView
	private CheckedTextView checktextview1;
	
	@Override
	protected void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);
		setContentView(R.layout.main);
		initialize();
	}
	
	private void initialize() {
		// initiate a CheckedTextView
		checktextview1 = findViewById(R.id.mainCheckedTextView);
		// set onClick listener for CheckedTextView
		checktextview1.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v1){
				// Toggle CheckedTextView when it is clicked
				checktextview1.toggle();
				// Show home button on ActionBar according to checked state of CheckedTextView
				getSupportActionBar().setDisplayHomeAsUpEnabled(checktextview1.isChecked());
			}
		});
	}
	
}

Output:
Now run the app. If you click on the CheckedTextView it will toggle between checked and unchecked states, and if it is checked it will make the home button on ActionBar visible.