I have an Activity
which launches an AlertDialog
with the following code. Unfortunately, the id that comes from the RadioGroup
as checked is always the ID of the first radio button, no matter which radio button was actually checked.
I suspect the problem is that the view has already been disposed of when the OK button is pressed, but I don't know why the string would still work if that were the case.
Why would this happen, and what could I do to get the actual radio button checked?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View v = getLayoutInflater().inflate(R.layout.dialog_add_team, null);
builder.setView(v);
// Add the buttons
builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String name = ((EditText) v.findViewById(R.id.team_name)).getText()+"";
if (name.equals(""))
return;
int checkedId=((RadioGroup)v.findViewById(R.id.radioGroup1))
.getCheckedRadioButtonId();
teamAdded(name, checkedId);
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
Here is the XML for my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/team_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/teamname" >
<requestFocus />
</EditText>
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/bothgenders" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boys" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/girls" />
</RadioGroup>
</LinearLayout>