如何获取列表中选择项的位置。我正在使用下面的代码。按下确定按钮后,我收到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();
}
答案 0 :(得分:2)
您想要的值是whichButton
OnClickListener
中的setSingleChoiceItems
(选项列表)。
问题是,如何跟踪它。可能有更优雅的解决方案,但这有效:
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();