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

Cách lấy chỉ số RadioButton được chọn trong RadioGroup Android

Giới thiệu

Ví dụ này minh họa cách lấy chỉ số (index) hoặc giá trị của RadioButton được chọn trong RadioGroup trong Android.

Các bước thực hiện

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

Mở Android Studio, chọn File → New Project và đ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"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="15dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvResult"
        android:text="Dịch vụ streaming yêu thích?"
        android:textSize="16sp"
        android:textStyle="bold" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:orientation="vertical"
        android:padding="15dp">

        <RadioButton
            android:id="@+id/rbNetflix"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Netflix"
            android:paddingRight="15dp" />

        <RadioButton
            android:id="@+id/rbAmazonPrime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Amazon Prime"
            android:paddingRight="15dp" />

        <RadioButton
            android:id="@+id/rbDisneyPlus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Disney+"
            android:paddingRight="15dp" />

        <RadioButton
            android:id="@+id/rbHBO"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="HBO Max"
            android:paddingRight="15dp" />

    </RadioGroup>

    <Button
        android:id="@+id/btnGetItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/radioGroup"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="Lấy lựa chọn" />

</RelativeLayout>

Bước 3: Viết code MainActivity.java

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

public class MainActivity extends AppCompatActivity {
    TextView tvResult;
    Button btnGetItem;
    RadioGroup radioGroup;

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

        tvResult = findViewById(R.id.tvResult);
        btnGetItem = findViewById(R.id.btnGetItem);
        radioGroup = findViewById(R.id.radioGroup);

        btnGetItem.setOnClickListener(v -> {
            int checkedId = radioGroup.getCheckedRadioButtonId();
            
            if (checkedId != -1) {
                // Cách 1: Lấy RadioButton và text
                RadioButton selectedRb = findViewById(checkedId);
                String selectedText = selectedRb.getText().toString();
                
                // Cách 2: Lấy index (vị trí) trong RadioGroup
                int index = radioGroup.indexOfChild(selectedRb);
                
                tvResult.setText(String.format("Đã chọn: %s (Index: %d)", selectedText, index));
            } else {
                tvResult.setText("Chưa chọn dịch vụ nào");
            }
        });

        // Lắng nghe thay đổi real-time
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton rb = findViewById(checkedId);
            if (rb != null) {
                tvResult.setText("Đang chọn: " + rb.getText());
            }
        });
    }
}

Các phương thức hữu ích của RadioGroup:

  • getCheckedRadioButtonId(): Trả về ID của RadioButton được chọn, -1 nếu không có
  • check(id): Chọn RadioButton theo ID
  • clearCheck(): Bỏ chọn tất cả
  • indexOfChild(view): Lấy index (0-based) của child view
  • getChildAt(index): Lấy view tại index
  • setOnCheckedChangeListener(): Lắng nghe thay đổi chọn

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Chọn một RadioButton và nhấn "Lấy lựa chọn" để xem kết quả.

Cách lấy chỉ số RadioButton được chọn trong RadioGroup Android

Cách lấy chỉ số RadioButton được chọn trong RadioGroup Android

Cách lấy chỉ số RadioButton được chọn trong RadioGroup Android