ปุ่มตัวเลือกช่วยให้ผู้ใช้เลือก 1 ตัวเลือกจากชุดตัวเลือกที่เลือกได้เพียงตัวเลือกเดียว ใช้ปุ่มตัวเลือกหากผู้ใช้จำเป็นต้องเห็นตัวเลือกที่มีทั้งหมดแสดงเป็นรายการ หากไม่จำเป็นต้องแสดงตัวเลือกทั้งหมด ให้ใช้ a Spinner แทน
หากต้องการสร้างตัวเลือกปุ่มตัวเลือกแต่ละรายการ ให้สร้าง RadioButton ในเลย์เอาต์ เนื่องจากปุ่มตัวเลือกเลือกได้เพียงตัวเลือกเดียว ให้จัดกลุ่มปุ่มตัวเลือกไว้ใน RadioGroup
ระบบจะตรวจสอบว่าเลือกปุ่มตัวเลือกภายในกลุ่มได้เพียงปุ่มเดียวต่อครั้ง
ตอบสนองต่อเหตุการณ์การคลิก
เมื่อผู้ใช้เลือกปุ่มตัวเลือก ออบเจ็กต์ RadioButton ที่เกี่ยวข้องจะได้รับเหตุการณ์การคลิก
ตัวอย่างต่อไปนี้แสดงการตอบสนองต่อการแตะออบเจ็กต์ RadioButton ของผู้ใช้ในกลุ่ม
<?xml version="1.0" encoding="utf-8"?> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/radio_pirates" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pirates"/> <RadioButton android:id="@+id/radio_ninjas" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ninjas"/> </RadioGroup>
ค้นหาปุ่มตัวเลือกและตั้งค่า Listener การเปลี่ยนแปลงสำหรับปุ่มตัวเลือกแต่ละปุ่มภายใน Activity หรือ Fragment ที่โฮสต์เลย์เอาต์นี้ ดังนี้
Kotlin
findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Pirates is checked: $isChecked") } findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Ninjas is checked: $isChecked") }
Java
findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Pirates is checked: $isChecked"); } findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Ninjas is checked: $isChecked"); }
ในตัวอย่างนี้ เมื่อผู้ใช้แตะปุ่มตัวเลือกปุ่มใดปุ่มหนึ่ง ระบบจะพิมพ์ข้อความใน Logcat