Home > DeveloperSection > Forums > Closing AlertDialog on select any option in android
Takeshi Okada
Takeshi Okada

Total Post:89

Points:629
Posted on    October-17-2014 12:19 AM

 Android Android 
Ratings:


 1 Reply(s)
 685  View(s)
Rate this:
I have this working piece of code for selecting a number from a GridView that's inside an AlertDialog:

public void iconSelect (View v){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    GridView gridview = new GridView(this);

    List<Integer>  mList = new ArrayList<Integer>();
    for (int i = 1; i < 10; i++) {
        mList.add(i);
    }
    ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
    gridview.setAdapter(adapter);
    gridview.setNumColumns(3);
    gridview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), "Chosen: " + position, Toast.LENGTH_SHORT).show();

        }
    });

    builder.setView(gridview);
    builder.setTitle("Icon selector");
    builder.show();
}
My goal is that when the user selects a number from the gridview then the dialog get closed. Right now it lets the user click the number on the gridview and show the toast many times as the user wants until he presses back button.

What should I do? I'm looking for a method similar to builder.close() or builder.dismiss() to be executed inside the listener. (Making builder a final variable)


Simons Hood
Simons Hood

Total Post:70

Points:494
Posted on    October-17-2014 12:20 AM

You should use builder.show() or builder.create() to hold an instance of AlertDialog in order to dismiss it after that

Try the following code:

public void iconSelect (View v){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    GridView gridview = new GridView(this);

    List<Integer>  mList = new ArrayList<Integer>();
    for (int i = 1; i < 10; i++) {
        mList.add(i);
    }
    ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
    gridview.setAdapter(adapter);
    gridview.setNumColumns(3);

    builder.setView(gridview);
    builder.setTitle("Icon selector");
    final AlertDialog dialog = builder.show();
    gridview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), "Chosen: " + position, Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        }
    });
}

Don't want to miss updates? Please click the below button!

Follow MindStick