Android/Java สร้าง RadioGroup และ RadioButton

ไฟล์ที่เกี่ยวข้อง

  • activity_main.xml
  • MainActivity.java

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/layoutMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.phaisarn.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity {

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

        String[] fruitOptions = {"Mango", "Papaya", "Orange", "Apple"};

        // create a radio group
        RadioGroup radioGroup = new RadioGroup(this);
        radioGroup.setOrientation(RadioGroup.VERTICAL);
        for (int i = 0; i < fruitOptions.length; i++) {
            // create a radio button
            RadioButton radioButton = new RadioButton(this);
            // set text for the radio button
            radioButton.setText(fruitOptions[i]);
            // assign an automatically generated id to the radio button
            radioButton.setId(View.generateViewId());
            // add radio button to the radio group
            radioGroup.addView(radioButton);
        }

        LinearLayout linearLayout = findViewById(R.id.layoutMain);
        linearLayout.addView(radioGroup);
    }
}

บรรทัดที่ 29 สร้างและกำหนด viewId ที่ไม่ซ้ำกันให้กับแต่ละ radioButton ด้วย View.generateViewId()