Blog Details

img
Design

how can use material checkbox in android

Spoke Right / 20 Nov, 2023

How can use material checkbox in android

Checkboxes are available in the Material library for Jetpack Compose. To facilitate the creation of the CheckBoxes, Android provides the android.widget.CheckBox class. Instead of using the default settings, we can also customize the UI of view elements in Android. Thus, different images of the checkbox can also be added to the layout. The CheckBox in Android can be understood as a type of two-state button. Here, the two-state means that it can be either checked or unchecked. Checkboxes can be used to serve various purposes such as selecting the hobbies of a user and to activate/deactivate a specific action. The CompoundButton class in Android has a subclass named CheckBox class.

Example of Custom CheckBox:

activity_main.xml: (File: activity_main.xml)



   
   
   
       
       
   
 
   
 
   
 
       
 
       
 
   
 

checked.xml:



 

 

 

 
   

unchecked.xml:



 
   
 
   
 
   
 

custom_checkbox.xml: (File: custom_checkbox.xml)

To customize the checkbox we will implement a selector in the checkbox.xml file under the drawable folder.



 
   
 
   
 
   
 

Activity class: (File: MainActivity.java)

package com.example.radioapp;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
 
public class MainActivity extends Activity implements OnClickListener {
 
   /** Called when the activity is first created. */
 
   @Override
 
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
 
       setContentView(R.layout.activity_main);
 
       findViewById(R.id.checkbox1).setOnClickListener(this);
       findViewById(R.id.checkbox2).setOnClickListener(this);
   }
 
   @Override
   public void onClick(View v) {
 
       TextView tv;
 
       if (v.getId()==R.id.checkbox1) {
 
           tv = (TextView)findViewById(R.id.textview1);
 
       } else {
 
           tv = (TextView)findViewById(R.id.textview2);
 
       }
 
       if (((CheckBox)v).isChecked()) {
 
           tv.setText("(checked)");
 
       } else {
 
           tv.setText("(unchecked)");
 
       }
 
   }
 
}

0 comments

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0