0

我正在使用setAdapter()on为我的列表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用于多项选择列表会产生误导。

4

2 回答 2

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;
}
于 2013-02-22T16:20:04.407 回答
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();
      }
};
于 2012-09-27T07:39:31.433 回答