How to get the id of selected radio button in android?

前端 未结 7 1884
遇见更好的自我
遇见更好的自我 2020-12-17 03:23

I am working on quiz application in android. We have created Select.java page which displays the questions and options(with radio buttons) from sqlite datab

相关标签:
7条回答
  • 2020-12-17 04:06

    Your layout xml file should be like this

    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
    
        <RadioGroup 
        android:orientation="vertical"
        android:id="@+id/radiogroup"
         android:layout_width="wrap_content"
      android:layout_height="wrap_content"
        >
        <RadioButton 
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/option1"
           android:text="Option1"
        />
        <RadioButton 
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/option2"
           android:text="Option2"
        />
        <RadioButton 
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/option3"
           android:text="Option3"
        />
        <RadioButton 
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/option4"
           android:text="Option4"
        />
        <RadioButton 
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/option5"
           android:text="Option5"
        />
        </RadioGroup>
    </LinearLayout>
    

    Add the below ode in your Activity

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) 
                {
                    RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId);
                    String text = checkedRadioButton.getText().toString();
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                }
            });
    
    0 讨论(0)
提交回复
热议问题