我有一个包含项目列表的Dialog Fragment。默认情况下,当您触摸某个项目时,该对话框将被忽略。我怎样才能防止此时被解雇? (我想在稍后阶段以编程方式关闭对话框)
我按照此处的指示关注代码示例:https://developer.android.com/guide/topics/ui/dialogs.html
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color)
.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
我看到有一个选项可以使用builder.setSingleChoiceItems
代替builder.setItems()
,这会给我我想要的行为,但不是风格。 (它带有单选按钮,我不想要)
答案 0 :(得分:1)
在创建对话框后在ListView
上设置一个监听器,如下所示:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = builder.setTitle("My dialog")
.setItems(new String[]{"Do nothing...", "Dismiss!"}, null) // any listener will do!
.create();
// add this listener after dialog creation to stop auto dismiss on selection
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position) {
case 0:
// do nothing selected
break;
case 1:
// dismiss selected
dialog.dismiss();
break;
}
}
};
dialog.getListView().setOnItemClickListener(listener);
return dialog;
}
答案 1 :(得分:0)
我认为你应该使用DialogFragment setItems
提供项目,但不是提供onClickListener的实例,而是提供null
。即:
.setItems(R.array.colors_array, null);
您可以根据需要稍后解除对话框。