0
我有一个Activity
,它使用以下代码启动AlertDialog
。不幸的是,来自RadioGroup
的编号为总是第一个单选按钮的ID,无论实际检查了哪个单选按钮。在关闭AlertDialog后获取单选按钮状态
我怀疑问题是,按下确定按钮时视图已经被丢弃,但我不知道为什么字符串仍然可以工作,如果是这种情况。
为什么会发生这种情况,我能做些什么来获得实际单选按钮?
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();
}
这里是我的布局XML:
<?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>
你知道我为什么做不起作用吗?我不需要知道支票何时更改,只有当用户按下确定时它的位置。 – 2013-04-27 20:28:51
如果没有侦听器,您无法检测到单击按钮,因此您需要侦听器。在侦听器的onCheckedChanged方法中,您可以检测所选的单选按钮。 – ACengiz 2013-04-27 20:32:51
那么getCheckedRadioButtonId()方法是什么? – 2013-04-27 20:34:23