Native Mobile App Development With Java

CheckedTextView Android

15-Sep-2024

Learn how to implement CheckedTextView in Android Studio Project Java

It looks like you're looking for a simpler example of how to use  CheckedTextView.


Here is the tutorial for Kotlin



Below is a minimal example: in  code.


There Are Some Common Attributes for CheckedTextView :


id
This is unique identity.
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size
textSize
Change The Text Size
textColor
Change Text Color
drawableLeft
Set Icon in Left
drawableRightSet Icon in Right
drawableTopSet Icon in Top
drawableBotomSet Icon in Botom
textStyle
bold, italic, normal -> Style Change
background
Set background Color


Step 1 :

File open res/layout/activity_main.xml file −



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">



<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_margin="10dp"
android:orientation="vertical">


<CheckedTextView
android:id="@+id/checkedTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20dp"
android:text="Check me" />
</LinearLayout>




</RelativeLayout>


Step 2 :

File open com.microappvalley.newtestproject/MainActivity.java file −

Java:


package com.microappvalley.newtestproject;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckedTextView;


public class MainActivity extends AppCompatActivity {

@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckedTextView checkedTextView = findViewById(R.id.checkedTextView);
checkedTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toggle the checked state when clicked
checkedTextView.setChecked(!checkedTextView.isChecked());

// Perform additional actions based on the checked state
if (checkedTextView.isChecked()) {
// Do something when checked
checkedTextView.setText("Checked!");
} else {
// Do something when unchecked
checkedTextView.setText("Check me");
}
}
});
}
}





Open Device Manager, run the emulator, and  then run the application. Next, check the working output and check the output  you declared in your code.


Output:




Comments