单击ListView项目时如何关闭AlertDialog

时间:2012-01-22 05:34:15

标签: android alertdialog alert

这是我的对话框代码,对话框中有ListView,我想在点击ListView时关闭此对话框:

public void createSearchDialog(final String[] Memo){
        LayoutInflater factory = LayoutInflater.from(this);
        View searchView = factory.inflate(R.layout.seach_dialog, null);

            lv = (ListView) searchView.findViewById(R.id.search_list);
        lv.setAdapter(new MyPerformanceArrayAdapter(this, Memo, memo_PW));
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
                // TODO Auto-generated method stub

                         /// close dialog
            }
        });


        searchBuilder = new AlertDialog.Builder(this);
        searchBuilder.setTitle("Search")
               .setView(searchView)
               .setNegativeButton("Back", new DialogInterface.OnClickListener() {               
                public void onClick(DialogInterface arg0, int arg1) {
                    // TODO Auto-generated method stub

                }
            })
               .show();     

    }

我尝试将此代码放在onItemClick()

    searchBuilder.create().dismiss();

    searchBuilder.create().cancel();

但它没有用。

3 个答案:

答案 0 :(得分:18)

.show()更改为dialog = searchBuilder.show();,然后将dialog.dismiss()更改为onItemClick()

答案 1 :(得分:1)

对于解除对话框.dismiss()将起作用。请检查您是否在适当的地方拨打此电话。如果您想在从ListView进行选择时关闭对话框,则需要关闭ListView的动作监听器中的对话框。

答案 2 :(得分:1)

完成此问题的代码

 public void showDialog(){
    final AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
    dialog.setTitle("Choose App");
    dialog.setCancelable(true);

    View view = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.custom_dialog_all_app, null);
    list = (ListView) view.findViewById(R.id.AllAppList);
    AllAppPckName = getPackages();
    AllAppListAdapter adapter= new AllAppListAdapter(getContext(), R.layout.app_item, AllAppPckName);

    list.setAdapter(adapter);

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            appIcon.setVisibility(View.VISIBLE);
            appIcon.setImageDrawable(getPackageIcon(getContext(), AllAppPckName.get(i)));
            appNameBtn.setText(getAppNameFromPkgName(getContext(), AllAppPckName.get(i)));

            dialogg.dismiss();


        }
    });


    dialog.setView(view);
    dialogg = dialog.show();
}