How to close AlertDialog when I click on a ListView element

Here is my dialog code, there is a dialog box ListView, I want to close this dialog box when I click 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();     

    }

I tried putting this code in onItemClick()

    searchBuilder.create().dismiss();

    searchBuilder.create().cancel();

But it does not work.

+5
source share
2 answers

Change .show()to dialog = searchBuilder.show();, then put dialog.dismiss()in onItemClick().

+15
source

Cancel the dialogue .dismiss()will work. Please check that you are calling the right place. if you want to close the dialog when the choice is made from yours ListView, then you need to cancel the dialog in the listener of your actions ListView.

+1
source

All Articles