Android Basic Training Course: Employing Basic Widgets

    Every GUI toolkit has some basic widgets: fields, labels, buttons, etc. Android’s toolkit is no different in scope, and the basic widgets will provide a good introduction as to how widgets work in Android activities.

1. Label

    The label widget in Android is TextView. A TextView is a complete text editor, however the basic class is configured to not allow editing. Typically, they are used to identify adjacent widgets (e.g., a “Name:” label before a field where one fills in a name).
    Normally, you can create a label by creating a TextView object in xml layout files. For example:
    TextView has numerous other properties of relevance for labels, such as:
  • android:text: the content of TextView - a string.
  • android:textSize: size of text displayed in TextView.
  • android:textColor: color of the text, it's value is a RGB hex format code (e.g: #34fde2).
    Output for layout above:

2. Button

    Button is a subclass of TextView, but you can set listener for it's click event. Basically, creating a Button instance in layout file is like TextView code above. And in Java code, handling it's event by setOnClickListener() method:
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //handling button click event
                //insert your codes here
            }
        });
    Note: you can declare a View.OnClickListener type method first:
private View.OnClickListener onButtonClick() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // handling click event
                // add some codes here
            }
        };
    }
    And attach it to the Button by this line:
button.setOnClickListener(onButtonClick());

3. Text Field

   Along with buttons and labels, text fields are the third “anchor” of most GUI toolkits. In Android, they are implemented via the EditText widget, which is a subclass of the TextView used for labels.
   It has many other attributes that will be useful for you in constructing fields, including:

  • android:hint: default text in EditText, disappear when you type another text in it.
  • android:capitalize: to control if the field should automatically capitalize the first letter of entered text (e.g: a person name).
  • android:inputType: to configure the input type of EditText. Some popular value: textPersonName, textPhoneNumber or textEmailAddress,...
  • android:singleLine: a boolean value, to control if the field is for single-line input or multiple-line input.
    For example:
    Java code for this layout:
package info.devexchanges.basicwidgets;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

        EditText editText = (EditText)findViewById(R.id.edit_text);
        editText.setText("Licensed under the Apache License, Version 2.0 \"\n" +
                "\t\t\t\t+ \"(the \\\"License\\\"); you may not use this file \"\n" +
                "\t\t\t\t+ \"except in compliance with the License. You may \"\n" +
                "\t\t\t\t+ \"obtain a copy of the License at \"\n" +
                "\t\t\t\t+ \"http://www.apache.org/licenses/LICENSE-2.0\n");
    }
}
    Running this demo app, we have this screen:

4. Images

    There are 2 widgets to display your images in your app: ImageView and ImageButton. Each widget has an attribute android:src (in XML layout) to specify the images to use. These properties often refer to drawables resource.
    Output of this layout:
    Note: Android SDK don't support well for Animated GIFs, to learn how to use this image format, please read this advance post.

5. CheckBox

    CheckBox is directly subclass of Button. CheckBox always in 1 of 2 status: check or uncheck. Click the small box to change that status to indicate selection. CheckBox has all TextView and Button attributes so you can use all properties of these widgets. In Java, there are some important methods:

  • setCheck(boolean value): set status for CheckBox, true is checked and false is unchecked.
  • isCheck(): return the CheckBox status (boolean value).
  • setOnCheckChangedListener(): most important method, listen changing CheckBox status event.
    Let's see this example layout:
    And it's programmatically code:
package info.devexchanges.basicwidgets;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        CheckBox checkBox = (CheckBox)findViewById(R.id.checkbox);

        checkBox.setOnCheckedChangeListener(onCheckChangeListener());
    }

    private CompoundButton.OnCheckedChangeListener onCheckChangeListener() {
        return new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
                if (isCheck) {
                    Toast.makeText(MainActivity.this, "Checked!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "unChecked!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    }
}
    Running app when we completed code:
    Note: There are some widgets similar with CheckBox is RadioButton, RadioGroup (set of check boxes with only one is selected at a time) and ToggleButton (from Android 4.0 it is Switch). Readers find out more, I'm not mention here.

5. DatePicker dialog

    Now, we learn an advance widget: DatePickerDialog. It allows you to select the date consisting of day, month and year in your custom user interface. DatePickerDialog is a simple dialog containing DatePicker, user select a Date by click in it.
    I present a simple project that showing a DatePickerDialog by click a Button. After user choose date value from DatePicker, app will set this date to a TextView. Design an xml layout includes a Button and TextView simple like this:
    In programmatically code, in onCreate() method of the Activity, we must set up a DatePickerDialog first:
        Calendar newCalendar = Calendar.getInstance();
        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                textView.setText("Selected Date: " + dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    As you can see, through an Calendar instance, we can get System Date Time. After choosing a date, onDateSet() will be called. In the code above, I update selected date to the TextView.
    After create this Dialog, if you want to show it after click the Button, invoke it by show():
datePickerDialog.show();
    Full code for this Activity:
package info.devexchanges.basicwidgets;

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

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private TextView textView;
    private DatePickerDialog datePickerDialog;

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

        button = (Button)findViewById(R.id.button);
        textView = (TextView)findViewById(R.id.text);

        setDatePicker();

        button.setOnClickListener(onClick());
    }

    private View.OnClickListener onClick() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePickerDialog.show();
            }
        };
    }

    private void setDatePicker() {
        Calendar newCalendar = Calendar.getInstance();
        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                textView.setText("Selected Date: " + dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    }
}
    Output of this demo project:

Note: The similar widget with DatePicker/DatePickerDialog is TimePicker/TimePickerDialog which by it, you can get System time (hour : minute : second).

6. Conclusions & References

    By this post, I've present some basic widgets which popular using in Android development. Further, you can check this widgets official doc to discover more. In next post, I will introduce some UI containers that includes these widgets in xml files.
    References to official docs:
- Button: http://developer.android.com/reference/android/widget/Button.html
- TextView: http://developer.android.com/reference/android/widget/TextView.html
- CheckBox: http://developer.android.com/reference/android/widget/CheckBox.html
- RadioButton: http://developer.android.com/reference/android/widget/RadioButton.html
- RadioGroup: http://developer.android.com/reference/android/widget/RadioGroup.html
- Switch: http://developer.android.com/reference/android/widget/Switch.html
- ToggleButton: http://developer.android.com/reference/android/widget/ToggleButton.html
- DatePickerDialog: http://developer.android.com/reference/android/app/DatePickerDialog.html


Share


Previous post
« Prev Post
Next post
Next Post »