I want to select just one radio button at a time, but after selecting one of them when I click on the other button they both are selected, what can I do to solve this problem.
My MainActivity.java code is
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
TextView text=(TextView)findViewById(R.id.txt1);
text.setText("Wrong Answer");
}
public void onClick1(View view) {
TextView text=(TextView)findViewById(R.id.txt1);
text.setText("You are Right");
}
}
RadioButton should be the direct child of RadioGroup, Otherwise grouping does not work.
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:id="@+id/radioGroup">
<RadioButton
android:layout_width="0dp"
android:layout_weight="50"
android:layout_height="wrap_content"
android:text="Debit"
android:id="@+id/rDebit"
android:checked="false"
/>
<RadioButton
android:layout_width="0dp"
android:layout_weight="50"
android:layout_height="wrap_content"
android:text="Credit"
android:id="@+id/rCredit"
android:checked="false" />
</RadioGroup>
And in java file
RadioGroup radioGroup;
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
do something
if (radioGroup.getCheckedRadioButtonId() == R.id.rCredit)
{
// do something
}
The accepted answer was deleted and cannot be undeleted. Probably because it was barely more than a link to an external site. So here is a more detailed version:
You need to group the radio buttons within the same RadioGroup
in your layout file.
See here: https://developer.android.com/guide/topics/ui/controls/radiobutton.html
Applied to your problem this could look like this:
<RadioGroup
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Dennis Ritchie" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick1"
android:text="James Gosling" />
</RadioGroup>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.