I have a radio group with radio button in an xml file:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked" />
<RadioButton
android:id="@+id/btn_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked" />
</RadioGroup>
How can I get a radio button by id? I tried:
RadioButton btn = (RadioButton)findViewById(R.id.btn_1)
But this throws a nullPointerException when I call setChecked()
method on btn
. Did I miss something?
You just need to call .findViewById()
on RadioGroup object. If you define radio group id as radioGroup
you can access individual button like this:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
View radioButton = radioGroup.findViewById(R.id.btn_1);
Other useful function would be radioGroup.getChildAt(int)