Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

RadioGroup trong Android là gì? Cách sử dụng cơ bản

Giới thiệu về RadioGroup

RadioGroup là container nhóm các RadioButton. Đặc điểm quan trọng: chỉ cho phép chọn một RadioButton tại một thời điểm. Khi chọn một button, các button khác trong cùng nhóm tự động bị bỏ chọn. Thích hợp cho các lựa chọn loại đơn (single choice) như giới tính, phương thức thanh toán, chủ đề yêu thích...

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chọn môn học yêu thích"
        android:textSize="20sp"
        android:padding="10dp" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <RadioButton
            android:id="@+id/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android" />

        <RadioButton
            android:id="@+id/java"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Java" />

        <RadioButton
            android:id="@+id/cpp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="C++" />

        <RadioButton
            android:id="@+id/c"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="C Programming" />

    </RadioGroup>

    <Button
        android:id="@+id/btnOk"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="OK" />

</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        final Button btnOk = findViewById(R.id.btnOk);
        final RadioGroup radioGroup = findViewById(R.id.radioGroup);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int checkedId = radioGroup.getCheckedRadioButtonId();

                if (checkedId == -1) {
                    // Không có lựa chọn nào
                    btnOk.setError("Vui lòng chọn một môn học");
                    Toast.makeText(MainActivity.this, "Chưa chọn môn học nào", Toast.LENGTH_SHORT).show();
                } else {
                    btnOk.setError(null);
                    RadioButton selectedRadioButton = findViewById(checkedId);
                    String selectedText = selectedRadioButton.getText().toString();
                    Toast.makeText(MainActivity.this, "Bạn chọn: " + selectedText, Toast.LENGTH_LONG).show();
                }
            }
        });

        // Bonus: Lắng nghe thay đổi lựa chọn real-time
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // Xử lý ngay khi người dùng chọn (nếu cần)
                // RadioButton rb = findViewById(checkedId);
            }
        });
    }
}

Chạy ứng dụng

Kết nối thiết bị và chạy ứng dụng.

RadioGroup trong Android là gì? Cách sử dụng cơ bản

Chọn môn học (ví dụ Java):

RadioGroup trong Android là gì? Cách sử dụng cơ bản

Nhấn OK để xác nhận:

RadioGroup trong Android là gì? Cách sử dụng cơ bản

Mẹo hay:
  • radioGroup.clearCheck(): Bỏ chọn tất cả
  • radioGroup.check(id): Chọn theo ID lập trình
  • Đặt android:checkedButton="@+id/default_id" trong XML để chọn mặc định
  • Dùng setOnCheckedChangeListener để phản hồi ngay lập tức
  • Có thể lồng RadioGroup trong ScrollView nếu nhiều lựa chọn