Question

how can i get this alert dialog to close if any of the list items where hit? I've been all over the net looking for the solution to this, and because there is not positive or negative button, I have no idea how to get access to the diologInterface object to call dismiss() on.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Sort by");
        ListView sortByList = new ListView(this);
        String[] listItems = getResources().getStringArray(R.array.sortByList);
        ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                listItems);
        sortByList.setAdapter(modeAdapter);
        builder.setView(sortByList).create().show();


        sortByList.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parrent, View v, int pos,
                    long id) {
                // I would like it if any of these items where clicked to remove the dialog. 
                switch(pos) {
                    case 0:
                        Log.d("recent", "was hit");
                        break;
                    case 1:
                        Log.d("title", "was hit");
                        break;
                    case 2:
                        Log.d("author", "was hit");
                        break;
                    }
        }});

any help on this would be greatly appreciated.

Was it helpful?

Solution

replace

builder.setView(sortByList).create().show();

by

final AlertDialog dialog = builder.setView(sortByList).create();
dialog.show();

Then, in the onItemClick method, add

dialog.dismiss();

Other solution (cleaner imho)

You could also use AlertDialog.Builder.setAdapter, which takes an adapter to display a ListView, and takes a listener to notify you. In that listener you receive a dialog that you can dismiss.

builder.setAdapter(modeAdapter, new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ### Here you can dismiss the dialog
            dialog.dismiss(); 
            switch(which) {
                case 0:
                    Log.d("recent", "was hit");
                    break;
                case 1:
                    Log.d("title", "was hit");
                    break;
                case 2:
                    Log.d("author", "was hit");
                    break;
            }
        }
    }).create().show();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top