ภาพรวม
ตัวอย่างนี้สาธิตการดึงดัชนี (Index) และข้อความของ RadioButton ที่ถูกเลือกใน RadioGroup เมื่อกดปุ่มยืนยัน
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="Select an option"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tvResult"
android:text="Which is your favorite streaming service?"
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:layout_marginTop="16dp"
android:orientation="vertical"
android:padding="16dp">
<RadioButton
android:id="@+id/rbNetflix"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="Netflix" />
<RadioButton
android:id="@+id/rbDisneyPlus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="Disney+" />
<RadioButton
android:id="@+id/rbHBO"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="HBO Max" />
<RadioButton
android:id="@+id/rbAmazonPrime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="Amazon Prime Video" />
<RadioButton
android:id="@+id/rbAppleTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="Apple TV+" />
</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="24dp"
android:text="Get Selected Item" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
private TextView tvResult;
private Button btnGetItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
tvResult = findViewById(R.id.tvResult);
btnGetItem = findViewById(R.id.btnGetItem);
btnGetItem.setOnClickListener(v -> getSelectedRadioButton());
// Optional: ฟังเหตุการณ์เปลี่ยนแปลงแบบ Real-time
radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
RadioButton selectedRb = findViewById(checkedId);
if (selectedRb != null) {
tvResult.setText("Selected: " + selectedRb.getText());
}
});
}
private void getSelectedRadioButton() {
int checkedId = radioGroup.getCheckedRadioButtonId();
if (checkedId != -1) {
// มี RadioButton ถูกเลือก
RadioButton selectedRadioButton = findViewById(checkedId);
String selectedText = selectedRadioButton.getText().toString();
// หา Index (0-based)
int index = radioGroup.indexOfChild(selectedRadioButton);
String message = String.format("Index: %d\nText: %s", index, selectedText);
tvResult.setText(message);
Toast.makeText(this, "Selected: " + selectedText, Toast.LENGTH_SHORT).show();
} else {
// ไม่มีอะไรถูกเลือก
tvResult.setText("Nothing selected");
Toast.makeText(this, "Please select an option", Toast.LENGTH_SHORT).show();
}
}
}
ขั้นตอนที่ 4: 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>
</intent-filter>
</activity>
</application>
</manifest>
การทดสอบ
รันแอป → เลือก RadioButton ใด RadioButton หนึ่ง → กดปุ่ม "Get Selected Item" → จะแสดง Index และข้อความ
เมธอดสำคัญของ RadioGroup
| Method | คำอธิบาย |
|---|---|
getCheckedRadioButtonId() | คืน View ID ของ RadioButton ที่เลือก (-1 ถ้าไม่มี) |
check(id) | เลือก RadioButton ตาม ID โดยโปรแกรม |
clearCheck() | ยกเลิกการเลือกทั้งหมด |
indexOfChild(view) | หา Index (0-based) ของ Child View |
getChildAt(index) | ดึง Child View ตาม Index |
getChildCount() | จำนวน RadioButton ทั้งหมด |
setOnCheckedChangeListener() | ฟังเหตุการณ์เปลี่ยนแปลงการเลือก |
การเข้าถึง RadioButton ทั้งหมดใน Group
// วนลูปอ่าน RadioButton ทั้งหมด
for (int i = 0; i < radioGroup.getChildCount(); i++) {
RadioButton rb = (RadioButton) radioGroup.getChildAt(i);
String text = rb.getText().toString();
boolean isChecked = rb.isChecked();
int id = rb.getId();
// ทำงานกับข้อมูล...
}
// หรือใช้ Stream (Java 8+)
List radioButtons = new ArrayList<>();
for (int i = 0; i < radioGroup.getChildCount(); i++) {
if (radioGroup.getChildAt(i) instanceof RadioButton) {
radioButtons.add((RadioButton) radioGroup.getChildAt(i));
}
}
// หา Index ของ RadioButton ที่เลือก
int selectedIndex = -1;
for (int i = 0; i < radioButtons.size(); i++) {
if (radioButtons.get(i).isChecked()) {
selectedIndex = i;
break;
}
}
💡 เคล็ดลับ: ใช้ Tag สำหรับเก็บค่าเพิ่มเติม
<RadioButton
android:id="@+id/rbNetflix"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="netflix" <!-- เก็บ Key/Value เพิ่มเติม -->
android:text="Netflix" />
// ในโค้ด
RadioButton selected = findViewById(radioGroup.getCheckedRadioButtonId());
String key = (String) selected.getTag(); // "netflix"
สำหรับ Kotlin
// Extension Function
fun RadioGroup.getSelectedIndex(): Int {
val checkedId = checkedRadioButtonId
return if (checkedId != -1) {
indexOfChild(findViewById(checkedId))
} else -1
}
fun RadioGroup.getSelectedText(): String? {
val checkedId = checkedRadioButtonId
return if (checkedId != -1) {
(findViewById(checkedId)).text.toString()
} else null
}
// ใช้งาน
val index = radioGroup.getSelectedIndex()
val text = radioGroup.getSelectedText()