我在setAdapter()
上使用AlertDialog.Builder
为我的列表提供我自己的自定义ListAdapter
。但在调用DialogInterface.OnClickListener()
后,对话框会自动被解除。
下面是AlertController.createListView(...)
中的Android源代码导致我的对话框被解雇:
if (mOnClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
mOnClickListener.onClick(dialog.mDialogInterface, position);
if (!mIsSingleChoice) {
dialog.mDialogInterface.dismiss();
}
}
});
}
目前我正在使用AlertDialog.Builder.setSingleChoiceItems(..)
而不是setAdapter(..)
。有没有更好的方法来使用自定义ListAdapter
并允许在对话框中进行多项选择?我发现将setSingleChoiceItems
用于多选列表会产生误导。
答案 0 :(得分:3)
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
m_adapter = new MyAdapter();
builder.setAdapter(m_adapter, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog alertDialog = builder.create();
// override default behavior of dismissing dialog on clicking list item
final ListView listView = alertDialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
return alertDialog;
}
答案 1 :(得分:2)
您可以使用Handler
类的任一方式关闭AlertDailog。请参阅以下代码
if (mOnClickListener != null)
{
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
mOnClickListener.onClick(dialog.mDialogInterface, position);
if (!mIsSingleChoice)
{
//dialog.mDialogInterface.dismiss();
// call handler class as follows,
handler.sendMessage(handler.obtainMessage());
}
}
});
}
private Handler handler = new Handler()
{
@Override
public void handleMessage ( Message message )
{
dialog.mDialogInterface.dismiss();
}
};