top of page

Learn Android App Dev: Using Checkbox

Hey there! This is Amey Lokhande. In this post I will be guiding you on how to use Checkboxes in your app. Generally Checkboxes are used when the user wants to select multiple items from a list of items. For ex, when you want to create an app for a grocery shop and you have to select multiple items then you can use Checkboxes.

Here are the steps on how to use Checkboxes:

1. Drag Checkbox from Widgets to your layout. Also drag a button which we will use to show the checked items. Then design your layout as follows:

2. Now I will explain the java Code for the app:

i) First of all, declare the checkbox and button variables in your Main Activity class.

ii) Now create a function which will give a toast message of which item is selected as soon as it is selected. Name it as, say ShowItems(). Cast the checkbox and button variables in it.

iii) Now create a setOnClickListener method for the button and inside the Argument for that method, let it be New OnClickListener. Then Android Studio will automatically generate some code for you. Now inside that method, create a new StringBuffer which will be used for showing the toast message.

So append the result from cucum, carrot, brinjal and tomato in your msg variable.

iv) Thats it! Our App is ready to run now. Here's screenshot of the running app:

The Java Code for this app:

public class MainActivity extends AppCompatActivity { private CheckBox cucum,carrot,tomato,brinjal; private Button btn;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ShowItems(); } public void ShowItems(){ cucum = (CheckBox)findViewById(R.id.checkBox); carrot = (CheckBox)findViewById(R.id.checkBox2); brinjal = (CheckBox)findViewById(R.id.checkBox3); tomato = (CheckBox)findViewById(R.id.checkBox4); btn = (Button)findViewById(R.id.button); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StringBuffer msg = new StringBuffer(); msg.append("Cucumber is :").append(cucum.isChecked()); msg.append("\nCarrot is :").append(carrot.isChecked()); msg.append("\nBrinjal is :").append(brinjal.isChecked()); msg.append("\nTomato is :").append(tomato.isChecked()); Toast.makeText(MainActivity.this,msg.toString(),Toast.LENGTH_LONG).show(); } }); } }

This it it! Thank you!


bottom of page