Andriod programming – Posts 7: Toast, CheckBox, RadioButton, Dialog

In this article I will guide you to perform the operation with a number of other basic subjects in Android. To do this all excited and not too monotonous, I will guide you to make an application to enroll at OTVINA Study with basic content as follows:

[qads]

android-register-form

The principle is this brief. When you fill full, we get all the information and inspection. If an error somewhere, then announced (by Toast) and started in again. If everything is OK, then display a success message Dialog! What begins now.

First we design interfaces. With the interface is not too complicated and almost only 1 evening (vertical) In this situation, we should choose LinearLayout is logical and easy to handle most.
Ah I also would recommend this to you the latest object at this point, so we'll add some libraries offline. You open the file build.gradle and additional libraries dependencies

android-build-gradle

    compile 'com.android.support:design:24.0.0'
    compile 'com.wdullaer:materialdatetimepicker:2.3.0'

The first library is a library designed to make beautiful Android some View, in this we use is EditText, Button.
Library stuff 2 the library by party 3 provides an interface to select the date beautiful

Then there will be 1 yellow gold above notification to alert you to synchronize and update project. You click Sync Now

android-sync-project

Now open the file activity_main.xml and start code

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="8dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:src="@drawable/logo" />

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/editName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/name" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/editPhone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/phone"
                android:inputType="phone" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/editEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/editAddress"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/address" />
        </android.support.design.widget.TextInputLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btnBirthDay"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/birthday" />

            <RadioGroup
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/radMale"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:checked="true"
                    android:text="@string/male" />

                <RadioButton
                    android:id="@+id/radFeMale"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/female" />
            </RadioGroup>
        </LinearLayout>

        <EditText
            android:id="@+id/editGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/group" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/course" />

        <CheckBox
            android:id="@+id/cbAndroid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/android" />

        <CheckBox
            android:id="@+id/cbWeb"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/web" />

        <CheckBox
            android:id="@+id/cbIC3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/ic3" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnOk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/ok" />
    </LinearLayout>
</ScrollView>

android-register-form-pre

In the code above to your attention to the following points:

  • Since we have a lot of content in this interface so with some small screen will not show all the data fields, so we use ScrollView, it allows us to pull up to the interface is enclosed in it (Here is the entire screen).
  • Object ImageView allows displaying an image. Here are photos Logo, you can Logo download here and for the folder /res/drawable.
  • android.support.design.widget.TextInputLayout combined with EditText will allow us to create a nice effect when click the EditText to import data.
  • In the EditText there are some attributes android:inputType, it helps the keyboard pops up in style. For example, when clicking on the type of phone that EditText, keyboard including numeric keypad pops up and the same character when you call.
  • RadioButton is a circular object, used to select one of the options, so we need to be heading into by RadioGroup otherwise you can choose many options at the same time as the Checkbox.
  • AppCompatButton object is inherited from Button and better effects
  • The entire text of his subjects are taken from @ string / abc news is taken from file /res/values/string.xml. We set the text in this aim can be reused when the code by the java (ie we may call from xml or java) or used in multiple languages ​​later.

File /res/values/string.xml như sau:

<resources>
    <string name="app_name">TUT7CheckBoxRaidoToast</string>

    <string name="name">Họ và tên(*)</string>
    <string name="phone">Điện thoại(*)</string>
    <string name="email">Email(*)</string>
    <string name="address">Địa chỉ(*)</string>
    <string name="birthday">Ngày sinh</string>
    <string name="male">Nam</string>
    <string name="female">Nữ</string>
    <string name="group">Nhóm với ai (nếu có)</string>
    <string name="course">Khóa học</string>
    <string name="android">Android</string>
    <string name="web">Web</string>
    <string name="ic3">IC3</string>

    <string name="ok">Xong</string>
    <string name="cancel">Hủy</string>

    <string name="please_enter_name">Bạn chưa nhập tên</string>
    <string name="please_enter_phone">Bạn chưa nhập điện thoại</string>
    <string name="please_enter_email">Bạn chưa nhập email</string>
    <string name="please_enter_address">Bạn chưa nhập địa chỉ</string>
    <string name="please_enter_birthday">Bạn chưa chọn ngày sinh</string>
    <string name="please_enter_course">Bạn chưa chọn khóa học</string>

    <string name="success">Thành công</string>
    <string name="notify_thanks">Cảm ơn bạn đã đăng ký khóa học {0}.\nChúng tôi sẽ gửi đến bạn những thông tin mới nhất sắp tới</string>

</resources>

Copy file logo.png vào /res/drawable
android-register-form-add-logo

That's it. Now turn to the only java code.

package com.nguyenvanquan7826.tut7checkboxraidotoast;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Context context;

    private EditText editName;
    private EditText editPhone;
    private EditText editEmail;
    private EditText editAddress;
    private EditText editGroup;

    private AppCompatButton btnBirthDay;

    private RadioButton radMale;
    private RadioButton radFemale;

    private CheckBox cbAndroid;
    private CheckBox cbWeb;
    private CheckBox cbIC3;

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

        context = this;

        connectView();
    }

    private void connectView() {
        editName = (EditText) findViewById(R.id.editName);
        editPhone = (EditText) findViewById(R.id.editPhone);
        editEmail = (EditText) findViewById(R.id.editEmail);
        editAddress = (EditText) findViewById(R.id.editAddress);
        editGroup = (EditText) findViewById(R.id.editGroup);

        btnBirthDay = (AppCompatButton) findViewById(R.id.btnBirthDay);
        btnBirthDay.setOnClickListener(this);
        findViewById(R.id.btnOk).setOnClickListener(this);

        radMale = (RadioButton) findViewById(R.id.radMale);
        radFemale = (RadioButton) findViewById(R.id.radFeMale);

        cbAndroid = (CheckBox) findViewById(R.id.cbAndroid);
        cbWeb = (CheckBox) findViewById(R.id.cbWeb);
        cbIC3 = (CheckBox) findViewById(R.id.cbIC3);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btnBirthDay:
                selectBirthDay();
                break;
            case R.id.btnOk:
                ok();
                break;
        }
    }

    private void selectBirthDay() {
        int defaultYear = 1990;
        int defaultMonth = 0;
        int defaultDate = 1;
        // create and setting Datapicker
        DatePickerDialog dpd = DatePickerDialog.newInstance(
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                        Calendar calendar = Calendar.getInstance();
                        // set select date for calendar
                        calendar.set(year, monthOfYear, dayOfMonth);

                        // config string format to show date
                        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

                        // set date for button birthday
                        btnBirthDay.setText(sdf.format(calendar.getTime()));
                    }
                },
                defaultYear,
                defaultMonth,
                defaultDate
        );
        dpd.setOkText(context.getResources().getString(R.string.ok));
        dpd.setCancelText(context.getResources().getString(R.string.cancel));

        // show datepicker
        dpd.show(getFragmentManager(), "DatePickerDialog");
    }

    private void ok() {
        // get data
        String name = editName.getText().toString().trim();
        String phone = editPhone.getText().toString().trim();
        String email = editEmail.getText().toString().trim();
        String address = editAddress.getText().toString().trim();
        String group = editGroup.getText().toString().trim();

        String birthDay = btnBirthDay.getText().toString().trim();
        String sex = radMale.isChecked() ? getString(context, R.string.male) : getString(R.string.female);
        String course = "";
        if (cbAndroid.isChecked()) {
            if (course.length() > 0) {
                course += ", ";
            }
            course += getString(R.string.android);
        }
        if (cbWeb.isChecked()) {
            if (course.length() > 0) {
                course += ", ";
            }
            course += getString(R.string.web);
        }
        if (cbIC3.isChecked()) {
            if (course.length() > 0) {
                course += ", ";
            }
            course += getString(R.string.ic3);
        }


        // check data
        if (TextUtils.isEmpty(name)) {
            editName.requestFocus();
            Toast.makeText(context, getString(R.string.please_enter_name), Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            editPhone.requestFocus();
            Toast.makeText(context, getString(R.string.please_enter_phone), Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(email)) {
            editEmail.requestFocus();
            Toast.makeText(context, getString(R.string.please_enter_email), Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(address)) {
            editAddress.requestFocus();
            Toast.makeText(context, getString(R.string.please_enter_address), Toast.LENGTH_SHORT).show();
            return;
        }

        if (birthDay.equals(getString(R.string.birthday))) {
            Toast.makeText(context, getString(R.string.please_enter_birthday), Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(course)) {
            Toast.makeText(context, getString(R.string.please_enter_course), Toast.LENGTH_SHORT).show();
            return;
        }

        // if all is ok, we process data and show dialog to notify

        String notifyThanks = getString(context, R.string.notify_thanks);
        notifyThanks = completeString(notifyThanks, new String[]{course});

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.success)
                .setMessage(notifyThanks)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // do something
                    }
                })
                .create()
                .show();
    }

    public static String getString(Context context, int id) {
        return context.getResources().getString(id);
    }

    public static String completeString(String source, String[] item) {
        for (int i = 0; i < item.length; i++) {
            source = source.replace("{" + i + "}", item[i]);
        }
        return source;
    }
}

In the code above, do you see 1 Context station, Please understand it is 1 contextual variables. All the action happens to a certain context. Example, to display 1 Toast (a quick notification) they also need to context (context). In many tutorials of, you can see them written as this or MainActivity.this, they are both here because I was assigned context = this already.
But there are many new code but I have annotated and also quite easy to read, the reader will understand the code quickly and severance!

Result:

android-register-form-ok