我在Sample AlertDialog中显示RadioButtons。
AlertDialog levelDialog;
final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Difficulty Level");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item)
{
case 0:
// Your code when first option selected
break;
case 1:
// Your code when 2nd option selected
break;
case 2:
break;
case 3:
break;
}
// levelDialog.dismiss();
}
});
builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
levelDialog = builder.create();
levelDialog.show();
我将此作为输出
我需要禁用第3个选项" HARD"。表示我想显示该项目,但不能选择。它应该处于禁用模式。
可以通过修改此代码来实现吗?或者我应该膨胀自定义布局并将其设置在builder.setView()?
上答案 0 :(得分:1)
另一种 hacky 方法是通过订阅对话框的onShow事件来获取对视图的引用,并更改onClick处理程序。
final AlertDialog levelDialog = builder.create();
final int itemPositionToDisable = 2;
levelDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
final ListView listView = levelDialog.getListView();
//Store a reference to the default listener. We need to call it for references that have not been disabled.
final AdapterView.OnItemClickListener defaultOnItemClickListener = listView.getOnItemClickListener();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position != itemPositionToDisable)
defaultOnItemClickListener.onItemClick(parent, view,position, id);
}
});
AppCompatCheckedTextView view = (AppCompatCheckedTextView) listView.getChildAt(itemPositionToDisable);
//Disable on click listener so that checkbox is not activated.
view.setOnClickListener(null);
//Disable the view.
view.setEnabled(false);
}
});
levelDialog.show();