CheckBox

CheckBox

  • A CheckBox is a special kind of button in Android which has two states either checked or unchecked.
  • The Checkbox is a very common widget to be used in Android and a very good example is the “Remember me” option in any kind of Login activity of an app which asks the user to activate or deactivate that service.
  • There are many other uses of the CheckBox widget like offering a list of options to the user to choose from and the options are mutually exclusive i.e., the user can select more than one option.
  • This feature of the CheckBox makes it a better option to be used in designing multiple-choice questions application or survey application in android.
  • CheckBox belongs to android.widget.CheckBox class. Android CheckBox class is the subclass of CompoundButton class.
  • It is generally used in a place where user can select one or more than choices from a given list of choices. For example, selecting hobbies.
 
  • Kotlin
package com.geeksforgeeks.checkbox; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.Toast; public class MainActivity extends AppCompatActivity { lateinit var ch : CheckBox lateinit var ch1 : CheckBox lateinit var ch2 : CheckBox lateinit var ch3 : CheckBox lateinit var btn : Button lateinit var msg = "" @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ch=findViewById(R.id.checkBox) ch1=findViewById(R.id.checkBox2) ch2=findViewById(R.id.checkBox3) ch3=findViewById(R.id.checkBox4) btn =findViewById(R.id.submit) btn.setOnClickListener{ // Concatenation of the checked options in if // isChecked() is used to check whether // the CheckBox is in true state or not. if(ch.isChecked()) msg = msg + " Painting "; if(ch1.isChecked()) msg = msg + " Reading "; if(ch2.isChecked()) msg = msg + " Singing "; if(ch3.isChecked()) msg = msg + " Cooking "; // Toast is created to display the // message using show() method. Toast.makeText(this, msg + "are selected",Toast.LENGTH_LONG).show(); } }