Creating a basic Android user interface

In this exercise we’re going to create a simple application that uses the following controls:

  • Button
  • Text field
  • Checkbox
  • Radio button
  • Spinner

The spinner will select between two languages, English and Tagalog and update the user interface in real time.

When the button is pressed it will display a message in the selected language.

The screens will look like:

Android UI excersise - English

Android UI excersise – Tagalog

Android UI excersise - Tagalog

Android UI excersise – English

Below the send button will appear the message that has been sent when the Send button is pressed.

First, create the following project in Android Studio and configure as per below:

Application name: Task Performance
Company domain: Your domain name
Project location: Path to your own folder

Set the minimum SDK to API 8: Android 2.2 (Froyo)

Create a blank activity with the following settings:

Activity name: TaskPerfActivity
Layout name: activity_task_perf

You can now update the relevant files in the project with the following and make sure you update the Tagalog translations in manifests\AndroidManifest.xml file.

The code:

The first file is the AndroidManifest.xml file. This one remains fairly standard as created.

manifests\AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edu.sti.taskperformance">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TaskPerfActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Next we create the layout. You can do this in two ways, one using the visual editor and dropping the controls where you want them or copy/paste the following into the activity_ask_perf.xml file. If you do choose the first option, you will need to make sure you name the controls as per the file here so the rest of the application will work.

res\layout\activity_ask_perf.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.sti.taskperformance.TaskPerfActivity"
    android:id="@+id/ljhkjh">

    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:prompt="@string/spinner_title"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Beautiful"
        android:id="@+id/cbxMagandaAko"
        android:layout_below="@+id/txtEmail"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:checked="false" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ugly"
        android:id="@+id/cbxPangitAko"
        android:checked="false"
        android:layout_below="@+id/cbxMagandaAko"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/btnSend"
        android:layout_marginTop="48dp"
        android:layout_below="@+id/cbxMagandaAko"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/spinner"
        android:layout_alignEnd="@+id/spinner"
        android:onClick="onSendButtonClicked" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="First Name"
        android:id="@+id/lblFirstName"
        android:layout_below="@+id/spinner"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Last Name"
        android:id="@+id/lblLastName"
        android:layout_below="@+id/lblFirstName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Email"
        android:id="@+id/lblEmail"
        android:layout_below="@+id/lblLastName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="16dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/txtFirstName"
        android:layout_alignBottom="@+id/lblFirstName"
        android:layout_alignRight="@+id/spinner"
        android:layout_alignEnd="@+id/spinner" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/txtLastName"
        android:layout_above="@+id/lblEmail"
        android:layout_alignLeft="@+id/txtFirstName"
        android:layout_alignStart="@+id/txtFirstName" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/txtEmail"
        android:layout_below="@+id/lblLastName"
        android:layout_alignLeft="@+id/txtLastName"
        android:layout_alignStart="@+id/txtLastName" />

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/cbxMagandaAko"
        android:layout_alignBottom="@+id/cbxPangitAko"
        android:layout_gravity="right"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/radioGroup">
        <RadioButton
            android:layout_width="136dp"
            android:layout_height="wrap_content"
            android:text="Girl"
            android:id="@+id/radGirl"
            android:onClick="onRadioButtonClicked" />
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Boy"
            android:id="@+id/radBoy"
            android:layout_below="@+id/radGirl"
            android:layout_alignRight="@+id/radGirl"
            android:layout_alignEnd="@+id/radGirl"
            android:onClick="onRadioButtonClicked" />
    </RadioGroup>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text=""
        android:id="@+id/txtResult"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_below="@+id/btnSend" />
</RelativeLayout>

manifests\AndroidManifest.xml

Now the fun begins. We create the code that actually makes things work. First step is to make sure all the imports are included. I’d probably suggest copying that section from the listing below first.

You will notice that the class is not quite the same as the default class that Android Studio created for you. This one extends Activity and it implements OnItemSelectedListener. This is part of the Spinner control.

package edu.sti.taskperformance;

import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import java.lang.String;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class TaskPerfActivity extends Activity implements OnItemSelectedListener {

    private String boyGirl = "";
    private String language = "English";
    private String result = "";
    private String isBeautiful = "";
    private String isUgly = "";

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

        // Spinner element
        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        // Spinner click listener
       // spinner.setOnItemSelectedListener(this);
        spinner.setOnItemSelectedListener(this);

        // Spinner Drop down elements
        List categories = new ArrayList();
        categories.add("English");
        categories.add("Tagalog");

        // Creating adapter for spinner
        ArrayAdapter dataAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, categories);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On selecting a spinner item
        String item = parent.getItemAtPosition(position).toString();
        // first create references to the controls we want to change based on language selection
        CheckBox cbxMagandaAko = (CheckBox)findViewById(R.id.cbxMagandaAko);
        CheckBox cbxPangitAko = (CheckBox)findViewById(R.id.cbxPangitAko);
        RadioButton radBoy = (RadioButton)findViewById(R.id.radBoy);
        RadioButton radGirl = (RadioButton)findViewById(R.id.radGirl);
        Button btnSend = (Button)findViewById(R.id.btnSend);
        TextView lblFirstName = (TextView)findViewById(R.id.lblFirstName);
        TextView lblLastName = (TextView)findViewById(R.id.lblLastName);
        TextView lblEmail = (TextView)findViewById(R.id.lblEmail);
        // Now we check to see if English selected and set labels to English
        if (item == "English") {
            cbxMagandaAko.setText("Beautiful");
            cbxPangitAko.setText("Ugly");
            radBoy.setText("Boy");
            radGirl.setText("Girl");
            btnSend.setText("SEND");
            lblFirstName.setText("First Name");
            lblLastName.setText("Last Name");
            lblEmail.setText("Email");
            language = "English";
        }
        else // if not English, must be Tagalog
        {
            cbxMagandaAko.setText("Magando ako");
            cbxPangitAko.setText("Pangit ako");
            radBoy.setText("Batang lalaki");
            radGirl.setText("batang babae");
            btnSend.setText("MAGPADALA");
            lblFirstName.setText("Pangalan");
            lblLastName.setText("Huling pangalan");
            lblEmail.setText("Email");
            language = "Tagalog";
        }

        // Showing selected spinner item
        {
            Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
        }
    }
    public void onNothingSelected(AdapterView<?> arg0) {
        // Auto-generated method stub
    }

    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.radBoy:
                if (checked)
                    boyGirl = "boy";
                    break;
            case R.id.radGirl:
                if (checked)
                    boyGirl = "girl";
                    break;
        }
    }

    public void onSendButtonClicked(View view) {
        // This will create the text to display at bottom of screen when the send button is clicked

        // first need to create references to the controls so you can access the data
        EditText txtFirstName = (EditText)findViewById(R.id.txtFirstName);
        EditText txtLastName = (EditText)findViewById(R.id.txtLastName);
        EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
        CheckBox cbxMagandaAko = (CheckBox)findViewById(R.id.cbxMagandaAko);
        CheckBox cbxPangitAko = (CheckBox)findViewById(R.id.cbxPangitAko);

        // See what check boxes are checked and set the variables


        // now check what language is being used
        if (language == "English") {
            // get the value from the check box and update variables
            if (cbxMagandaAko.isChecked())
                isBeautiful = "is beautiful";
            else
                isBeautiful = "is not beautiful";
            if (cbxPangitAko.isChecked())
                isUgly = "is ugly";
            else
                isUgly = "is not ugly";
            // create the string to display
            result = "Sent message to " + txtEmail.getText() + " that " + txtFirstName.getText();
            result = result + " " + txtLastName.getText() + " is a ";
            result = result + boyGirl + " and " + isBeautiful + " and " + isUgly;
        }
        else // the language is not English so must be Tagalog
        {
            // TODO You should check the strings (green text) to make sure they are correct Tagalog
            // get the value from the check box and update variables
            if (cbxMagandaAko.isChecked())
                isBeautiful = "ay maganda";
            else
                isBeautiful = "hindi maganda";
            if (cbxPangitAko.isChecked())
                isUgly = "ay pangit";
            else
                isUgly = "hindi pangit";
            // create the string to display
            result = "Ipinadala mensahe sa " + txtEmail.getText() + " na " + txtFirstName.getText();
            result = result + " " + txtLastName.getText() + " ay isang ";
            result = result + boyGirl + " at " + isBeautiful + " at " + isUgly;
        }
        // create reference for the text field at bottom used to display result
        TextView txtResult = (TextView)findViewById(R.id.txtResult);
        // display the string at bottom part of the screen
        txtResult.setText(result.toString());
    }
}

res\values\strings.xml

<resources>
    <string name="app_name">Task Performance</string>
    <string name="action_settings">Settings</string>
    <string name="spinner_title">Settings</string>
</resources>

 

This entry was posted in Android. Bookmark the permalink.