In Android, you can use “android.widget.CheckBox” class to render a checkbox.
In this tutorial, we show you how to create 3 checkboxes in XML file, and demonstrates the use of listener to check the checkbox state – checked or unchecked.
Open “your.xml” file, just add add 3 “CheckBox” and a button, inside the LinearLayout.
<!--?xml version= "1.0" encoding= "utf-8" ?--> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:orientation= "vertical" > <checkbox android:id= "@+id/chkIos" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@string/chk_ios" > <checkbox android:id= "@+id/chkAndroid" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@string/chk_android" android:checked= "true" > <checkbox android:id= "@+id/chkWindows" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@string/chk_windows" > <button android:id= "@+id/btnDisplay" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@string/btn_display" > //Put android:checked="true" inside checkbox element to make it checked bu default. // In this case, "Android" option is checked by default.</button></checkbox></checkbox></checkbox></linearlayout> |
Attach listeners inside your activity “onCreate()” method, to monitor following events :
If checkbox id : “chkIos” is checked, display a floating box with message “Bro, try Android”.
If button is is clicked, display a floating box and display the checkbox states.
public class MainActivity extends Activity { private CheckBox chkIos, chkAndroid, chkWindows; private Button btnDisplay; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); addListenerOnChkIos(); addListenerOnButton(); } public void addListenerOnChkIos() { chkIos = (CheckBox) findViewById(R.id.chkIos); chkIos.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { //is chkIos checked? if (((CheckBox) v).isChecked()) { Toast.makeText(MyAndroidAppActivity. this , "Bro, try Android :)" , Toast.LENGTH_LONG).show(); } } }); } public void addListenerOnButton() { chkIos = (CheckBox) findViewById(R.id.chkIos); chkAndroid = (CheckBox) findViewById(R.id.chkAndroid); chkWindows = (CheckBox) findViewById(R.id.chkWindows); btnDisplay = (Button) findViewById(R.id.btnDisplay); btnDisplay.setOnClickListener( new OnClickListener() { //Run when button is clicked @Override public void onClick(View v) { StringBuffer result = new StringBuffer(); result.append( "IPhone check : " ).append(chkIos.isChecked()); result.append( "\nAndroid check : " ).append(chkAndroid.isChecked()); result.append( "\nWindows Mobile check :" ).append(chkWindows.isChecked()); Toast.makeText(MyAndroidAppActivity. this , result.toString(), Toast.LENGTH_LONG).show(); } }); } } |