Thứ Hai, 7 tháng 7, 2014

Bài 9: Ví dụ tổng hợp CheckBox, RadioButton, Button, EditText...

     Trong bài trước, các bạn đã tìm hiểu và nắm bắt được các control CheckBox, RadioButton. Trong bài này, chúng ta cùng làm ví dụ tổng hợp CheckBox, RadioButton, Button, Editext... giúp chúng ta củng cố lại kiến thức đã học.

- Ví dụ: đăng ký thông tin tìm bạn bốn phương. Yêu cầu nhập họ tên, email, giới tính và một vài thông tin khác. Ứng dụng sẽ có 2 nút là OK và Clear. Khi nhấn vào nút Ok sẽ hiện ra một hộp hội thoại AlertDialog để thông báo các thông tin đã được nạp vào. Nút Clear để xóa trắng các trường thông tin.
- Các bạn xem giao diện sau để dễ hình dung và thiết kế giao diện:
Ví dụ tổng hợp CheckBox, RadioButton, Button, Editext...
- Chúng ta sử dụng CheckBox để xác định giới tính, và RadioButton để nhập đối tượng quan tâm. Các bạn cần nhóm 2 CheckBox lại vào một RadioGroup để tiện xử lý. Sau đây là code của chương trình.
+activity_main.xml

<ScrollView 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">
   
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context="com.example.checkboxradiobutton.MainActivity$PlaceholderFragment" >

    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#008000"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        android:gravity="center"
        android:text="Đăng ký tìm bạn bốn phương"/>
   
    <TableLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="*">
        <TableRow android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5sp"
            android:layout_marginLeft="5sp">
           
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Họ tên: "/>
            <EditText
                android:id="@+id/edtHoTen"
                 android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="8"
                android:inputType="text">
                <requestFocus/>
            </EditText>
        </TableRow>
        <TableRow android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5sp"
            android:layout_marginLeft="5sp">
           
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Email liên lạc: "/>
            <EditText
                android:id="@+id/edtEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="8"
                android:inputType="text">
            </EditText>
        </TableRow>
        <TableRow android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5sp"
            android:layout_marginLeft="5sp">
           
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:text="Giới tính "/>
            <RadioGroup android:id="@+id/rgGioiTinh"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <RadioButton android:id="@+id/rbNam"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Nam"
                    android:checked="true"/>
                <RadioButton android:id="@+id/rbNam"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Nữ"/>
            </RadioGroup>
        </TableRow>
       
        <TableRow android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5sp"
            android:layout_marginLeft="5sp">
           
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Năm sinh "/>
           
            <EditText
                android:id="@+id/edtNamSinh"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="8"
                android:inputType="number">
            </EditText>
        </TableRow>
    </TableLayout>
   
    <TextView
        android:layout_marginTop="10sp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#9230f3"
        android:text="Đối tượng quan tâm"/>
   
    <RadioGroup android:id="@+id/rgDoiTuong"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       
        <CheckBox android:id="@+id/cbNam"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nam"/>
        <CheckBox android:id="@+id/cbNu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nữ"/>
        <CheckBox android:id="@+id/cbGay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gay"/>
        <CheckBox android:id="@+id/cbLes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Les"/>
    </RadioGroup>
   
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button android:id="@+id/btnOK"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="OK"/>
           <Button android:id="@+id/btnClear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Clear"/>
    </LinearLayout>
</LinearLayout>
   
</ScrollView>

Chúng ta sử dụng ScrollView bao trùm ngoài LinearLayout, ScrollView sẽ giúp chúng ta kéo được màn hình nếu ứng dụng của chúng ta vượt quá chiều dài màn hình. Tuy nhiên, bên trong ScrollView chỉ cho phép 1 control nên chúng ta bao toàn bộ các control khác trong LinearLayout. Các bạn cần chú ý và ghi nhớ đặc điểm này của ScrollView vì nếu không làm như vậy sẽ nhận được báo lỗi.

+MainActivity.java:

package com.example.checkboxradiobutton;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    Button btnOK, btnClear;
    EditText edtHoten, edtEmail, edtNamSinh;
    RadioGroup rgGioiTinh;
    CheckBox cbNam, cbNu, cbGay, cbLes;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        getControlView();
       
        btnOK.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                xuLyNhap();
            }
        });
        btnClear.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                xuLyXoa();
            }
        });
       
    }
    private void getControlView() {
        // TODO Auto-generated method stub
        btnOK = (Button)findViewById(R.id.btnOK);
        btnClear = (Button)findViewById(R.id.btnClear);
        edtHoten = (EditText)findViewById(R.id.edtHoTen);
        edtEmail = (EditText)findViewById(R.id.edtEmail);
        edtNamSinh = (EditText)findViewById(R.id.edtNamSinh);
        rgGioiTinh = (RadioGroup)findViewById(R.id.rgGioiTinh);
        cbNam = (CheckBox)findViewById(R.id.cbNam);
        cbNu = (CheckBox)findViewById(R.id.cbNu);
        cbLes = (CheckBox)findViewById(R.id.cbLes);
        cbGay = (CheckBox)findViewById(R.id.cbGay);
    }
   
    protected void xuLyNhap() {
        // TODO Auto-generated method stub
        String hoTen = edtHoten.getText().toString();
        String email = edtEmail.getText().toString();
        String namsinh = edtNamSinh.getText().toString();
        if(hoTen==null || hoTen.equalsIgnoreCase("") ){
            Toast.makeText(getBaseContext(), "Bạn phải nhập họ tên", Toast.LENGTH_LONG).show();
            return;
        }
        if(email==null || email.equalsIgnoreCase("")){
            Toast.makeText(getBaseContext(), "Bạn phải nhập email", Toast.LENGTH_LONG).show();
            return;
        }
        if(namsinh==null || namsinh.equalsIgnoreCase("")){
            Toast.makeText(getBaseContext(), "Bạn phải nhập năm sinh", Toast.LENGTH_LONG).show();
            return;
        }
       
        String gioiTinh;
        if(rgGioiTinh.getCheckedRadioButtonId()==R.id.rbNam){
            gioiTinh = "Nam";
        }else{
            gioiTinh = "Nữ";
        }
       
        String doiTuongQuanTam = "";
        if(cbNam.isChecked()){
            doiTuongQuanTam += "Nam"+"; ";
        }
        if(cbNu.isChecked()){
            doiTuongQuanTam += "Nữ"+"; ";
        }
        if(cbLes.isChecked()){
            doiTuongQuanTam += "Les"+"; ";
        }
        if(cbGay.isChecked()){
            doiTuongQuanTam += "Gay"+"; ";
        }
       
        if(doiTuongQuanTam == null || doiTuongQuanTam.equalsIgnoreCase("") ){
            Toast.makeText(getBaseContext(), "Bạn cần chọn đối tượng quan tâm", Toast.LENGTH_LONG).show();
            return;
        }
       
        AlertDialog.Builder ad = new AlertDialog.Builder(this);
        ad.setTitle("Thông tin cá nhân");
        ad.setPositiveButton("Close", new DialogInterface.OnClickListener() {
           
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.cancel();
            }
        });
        String message = "";
        message += "Họ tên: "+hoTen + "\n";
        message += "Email: "+email + "\n";
        message += "Giới tính: "+gioiTinh + "\n";
        message += "Năm sinh: "+namsinh + "\n";
        message += "Đối tượng quan tâm : "+doiTuongQuanTam + "\n";
       
        ad.setMessage(message);
        ad.create().show();
    }

    protected void xuLyXoa() {
        // TODO Auto-generated method stub
        edtHoten.setText("");
        edtNamSinh.setText("");
        edtEmail.setText("");
        cbNam.setChecked(false);
        cbNu.setChecked(false);
        cbLes.setChecked(false);
        cbGay.setChecked(false);
       
    }
}

Các bạn lưu ý đoạn code xử lý CheckBox, RadioButton và tạo hộp hội thoại AlertDialog. Đây đều là các control rất cơ bản và thường được sử dụng thường xuyên trong các ứng dụng Android. Việc nắm vững các kiến thức về những loại control này là rất quan trọng. Các bạn nên tự mình code lại bài tập này sau khi đã đọc kỹ và tự mầy mò tạo ra thêm các ví dụ khác về các control này nhé.

>>>Bài 10:Thêm một ví dụ về TextView, EditText, CheckBox, Button và ImageButton trong Android

Bài 8: Cách sử dụng Checkbox, Radio Button trong Android

     Trong bài tập này, chúng ta cùng tìm hiểu về 2 thành phần: CheckBox RadioButton. Đây là 2 control thường xuyên được chúng ta sử dụng trong các chương trình.



- Một số phương thức thường sử dụng của CheckBox RadioButton:
 + Phương thức setChecked dùng để thiết lập việc checked. Nếu bạn gọi setChecked(true) thì có nghĩa là bạn cho phép CheckBox hoặc RadioButton được checked, và ngược lại setChecked(false) sẽ unchecked 2 control này.
 + Phương thức isChecked: Trả về một giá trị boolean: True hoặc False. Nếu control đang được check sẽ trả về giá trị True, và ngược lại unchecked trả về là False

- Cả CheckBox và RadioButton thường được thiết kế trong một RadioGroup. RadioGroup nhóm các CheckBox và RadioButton lại và thường dùng cho một mục đích nào đó. Tuy nhiên, CheckBox cho phép chúng ta checked nhiều đối tượng còn RadioButton thì tại một thời điểm chỉ cho phép ta checked 1 đối tượng trong cùng một group mà thôi.

- Các bạn xem hình sau để hiểu rõ hơn về CheckBox. Đây là ví dụ khi bạn muốn người sử dụng chọn lựa nhiều trường hợp do bạn đưa ra trong CheckBox.
CheckBox trong android
- Bạn cũng có thể thiết lập trạng thái checked cho CheckBox trong xml như sau :

<CheckBox android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Brazil"
            android:checked="true"/>

- Nếu bạn chỉ muốn người sử dụng chọn 1 trong các trường hợp mà bạn đưa ra thì bạn sử dụng RadioButton. RadioButton chỉ cho phép chọn 1 trong RadioGroup.
RadioButton trong Android
 - Các bạn xem cách thiết kế một RadioGroup
<RadioGroup android:id="@+id/rg1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
       
        <RadioButton android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Brazil"/>
       
        <RadioButton android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Đức"/>
       
        <RadioButton android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Italia"/>
       
        <RadioButton android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Việt Nam"/>
       
    </RadioGroup>
 
- Dựa vào ví dụ thiết kế trên, các bạn đã hình dung và biết cách sử dụng RadioGroup để gom nhóm các RadioButton hoặc CheckBox vào thành một nhóm nào đó. Bởi vì RadioButton mà cùng một nhóm thì tại cùng thời điểm chỉ có 1 RadioButton được checked nên bạn có thể tạo nhiều nhóm RadioGroup để xử lý với các mục đích khác nhau

- Chúng ta có 2 cách để xử lý RadioButton nào được checked:
 + C1: Dựa vào RadioGroup để biết ID nào của RadioButton được checked. Dựa vào ID này chúng ta sẽ xử lý code theo những gì chúng ta mong muốn

        RadioGroup rg = (RadioGroup) findViewById(R.id.rg1);
        int idRadioButtonChecked = rg.getCheckedRadioButtonId();
        switch (idRadioButtonChecked) {
        case R.id.rbBrazil:
            break;
        case R.id.rbDuc:
            break;
        case R.id.rbItalia:
            break;
        case R.id.rbVietNam:
            break;
        }
 + C2: Check trực tiếp xem RadioButton đó có được cheked hay không
        RadioButton rbDuc = (RadioButton)findViewById(R.id.rbDuc);
        if(rbDuc.isChecked()){
            //Xử lý với trạng thái checked
        }else{
            //Xử lý với trạng thái unchecked
        }

      Qua bài tập này, các bạn đã hiểu và biết cách sử dụng 2 control CheckBox và RadioButton. Trong bài tập sau, mình sẽ demo thêm ví dụ về CheckBox, RadioButton, Button, Editext để các bạn nắm vững hơn kiến thức về các control cơ bản này. Hẹn gặp lại các bạn ở các bài tiếp theo !

>>>Bài 9: Ví dụ tổng hợp CheckBox, RadioButton, Button, EditText...

Bài đăng phổ biến