Android 按下“确定”按钮时,如何在单个选项列表中获取选择位置?
如何获取列表中选定项的位置。我正在使用下面的代码。按下“确定”按钮时,我得到了Android 按下“确定”按钮时,如何在单个选项列表中获取选择位置?,android,android-widget,Android,Android Widget,如何获取列表中选定项的位置。我正在使用下面的代码。按下“确定”按钮时,我得到了int whichButton。但它总是显示-1 private void filterByLocationDialog(final String[] items){ AlertDialog alert = new AlertDialog.Builder(PictureCollectionActivity.this) .setIcon(R.drawable.icon) .
int whichButton
。但它总是显示-1
private void filterByLocationDialog(final String[] items){
AlertDialog alert = new AlertDialog.Builder(PictureCollectionActivity.this)
.setIcon(R.drawable.icon)
.setTitle("Select a Location")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(PictureCollectionActivity.this, "Now"+whichButton, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
})
.create();
alert.show();
}
所需的值是
设置SingleChoiceItems
中的OnClickListener
中的which按钮(选项列表)
问题是,如何跟踪它。可能有更优雅的解决方案,但这是可行的:
final int[] selected = new int[1];
AlertDialog alert = new AlertDialog.Builder(this)
.setTitle("Select a Location")
.setSingleChoiceItems(items, 0,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
selected[0] = whichButton;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(WeightTestActivity.this,
"Now" + selected[0], Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked No so do some stuff */
}
}).create();
alert.show();
嗯,我也是这么想的。谢谢你的时间