Beginning Android Studio 4. CheckBox

Introduction

Welcome to the fourth tutorial in the Beginning Android Studio series. In the last tutorial, you learned about ImageButtons. In this tutorial, we will learn how to work with CheckBoxes. Here's what we will be doing this time:

 

 

Getting started

For this project, as seen in the video above, we need three checkboxes, one button and two textviews. Start by dragging those out on the screen. I omit to give the first textview an ID, since we're not going to change it. The checkboxes however, are given the IDs frogCheckBox, catCheckBox and dogCheckBox, with the text "Frogs", "Cats" and "Dogs" respectively. The button is given the ID submitBtn and a text "SUBMIT". The last textview is given the ID submitTxt, with no text at all.

I change the textSize of the first textview saying "What animals do you like?" to 30sp, and the bottom textview to 18sp. The button gets another background, #adb2bf. You can change this in xml:

<!-- buttons background  -->
android:background="#adb2bf"

<!-- title size -->
android:textSize="30sp"

<!-- submitted text size -->
android:textSize="18sp"

 

Here is the full activity_main.xml that I use:

<?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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="78dp"
        android:text="What animals do you like?"
        android:textSize="30sp" />

    <CheckBox
        android:id="@+id/frogCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/textView"
        android:layout_alignLeft="@+id/textView"
        android:layout_marginTop="152dp"
        android:text="Frogs" />

    <CheckBox
        android:id="@+id/catCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/textView"
        android:layout_alignLeft="@+id/textView"
        android:layout_marginTop="199dp"
        android:text="Cats" />

    <CheckBox
        android:id="@+id/dogCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/textView"
        android:layout_alignLeft="@+id/textView"
        android:layout_marginTop="246dp"
        android:text="Dogs" />

    <Button
        android:id="@+id/submitBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#adb2bf"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="204dp"
        android:text="Submit" />

    <TextView
        android:id="@+id/submitTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="145dp"
        android:textSize="18sp" />
</RelativeLayout>

 

The default color for checkboxes that are checked is pink. You might want to change this, and to do that, we open up app/res/values/styles.xml. Locate the line:

        <item name="colorAccent">@color/colorAccent</item>

You can change this to any color you want, I'm going to use the color #adb2bf:

        <item name="colorAccent">#adb2bf</item>

That's everything it for the design. Let's write some code that lets us interact with it.

 

Leaving XML for Java

Open up MainActivity.java. Pause for a second and think about what we want to accomplish. We have three checkboxes, a button and a textview for output. When we click on the button, we want the output to display something based on how the checkboxes are set up. If some or all of the boxes are checked, we want the text to start with "You like: " followed by the animals that are checked. If no boxes are checked, the output should display "You don't like animals. Animal hater."

It feels reasonable to create a function that returns a String with the output:

public String getSubmitText(CheckBox frogBox, CheckBox catBox, CheckBox dogBox) {
        boolean firstCheck = false;
        String output = "You like: ";
}

 

If both frog and cat is checked, the text should say "Frog and cats". If only one of those are checked, the text should say either "Frogs" or Cats". And for that reason, we will make use of a boolean as shown in the code above. Frog will always come first, so we don't have to check this boolean when checking the state of the frogs checkbox. If it is checked, however, we should change the boolean to true so the next variable can begin with "and":

        if (frogBox.isChecked()) {
            firstCheck = true;
            output += "Frogs";
        }

 

The line output += "Frogs"; is equivalent to:

output += frogBox.getText().toString();

in this case, but it's more readable to just write output += "Frogs"; so let us stick with that.

If the cats checkbox is checked, first thing we want to do is to check the state of our boolean. If it's true, we add " and cats" to our output, if it's false, we make it true and add "Cats" instead:

        if (catBox.isChecked()) {
            if (firstCheck) {
                output += " and cats";
            } else {
                firstCheck = true;
                output += "Cats";
            }
        }

The dogs checkbox follow the same principle. After all of the boxes have been checked, we check if the boolean is still false (meaning every checkbox was unchecked:

        if (!firstCheck) {
            output = "You don't like animals. Animal hater.";
        }

 

And our function is done. Now we want our function to cooperate with the button we created. Start with the variables that connects to the design, I'm putting this in the onCreate function:

        final CheckBox frogCheckBox = findViewById(R.id.frogCheckBox);
        final CheckBox catCheckBox = findViewById(R.id.catCheckBox);
        final CheckBox dogCheckBox = findViewById(R.id.dogCheckBox);
        final TextView submitTxt = findViewById(R.id.submitTxt);
        Button submitBtn = findViewById(R.id.submitBtn);

 

All we need to do now is to create a clickListener for the button, and make the submitTxt display the text that the function we created will spit out:

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String output = getSubmitText(frogCheckBox, catCheckBox, dogCheckBox);
                submitTxt.setText(output);
            }
        });

 

And that's it! Here's the full MainActivity.java:

package com.hallucind.tutorials.checkbox;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CheckBox frogCheckBox = findViewById(R.id.frogCheckBox);
        final CheckBox catCheckBox = findViewById(R.id.catCheckBox);
        final CheckBox dogCheckBox = findViewById(R.id.dogCheckBox);
        final TextView submitTxt = findViewById(R.id.submitTxt);
        Button submitBtn = findViewById(R.id.submitBtn);

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String output = getSubmitText(frogCheckBox, catCheckBox, dogCheckBox);
                submitTxt.setText(output);
            }
        });
    }

    public String getSubmitText(CheckBox frogBox, CheckBox catBox, CheckBox dogBox) {
        boolean firstCheck = false;
        String output = "You like: ";

        if (frogBox.isChecked()) {
            firstCheck = true;
            output += "Frogs";
        }

        if (catBox.isChecked()) {
            if (firstCheck) {
                output += " and cats";
            } else {
                firstCheck = true;
                output += "Cats";
            }
        }

        if (dogBox.isChecked()) {
            if (firstCheck) {
                output += " and dogs";
            } else {
                firstCheck = true;
                output += "Dogs";
            }
        }

        if (!firstCheck) {
            output = "You don't like animals. Animal hater.";
        }

        return output;
    }
}

 

Having trouble? Maybe this video can help you:

 

Enjoyed this article? Give the teacher an apple.

cookie

0

Author

authors profile photo

Articles with similar tags

Comments