Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an AlertDialog.Builder selected item click event?

I want to implement AlertDialog.Builder selected items click event. Below is what I have tried so far. I'm quite new to Android and I'm not sure how to access that event. How to implement the click event for each individual item in the list?

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class MakeCallAlertDialog {

    public static AlertDialog.Builder getAlertDialog(String strArray[],
            String strTitle, Activity activity) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
        alertDialogBuilder.setTitle(strTitle);
        alertDialogBuilder.setItems(strArray, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int arg) {
                // TODO Auto-generated method stub
            }
        });

        return alertDialogBuilder;
    }
}
like image 993
Gayan Kalanamith Avatar asked Jan 17 '26 07:01

Gayan Kalanamith


2 Answers

Since you assigned an OnClickListener specific to that method, the int parameter is the position in the list:

Parameters

dialog The dialog that received the click.

which The button that was clicked (e.g. BUTTON1) or the position of the item clicked

This means inside your method, you should be able to do this:

public static AlertDialog.Builder getAlertDialog(final String strArray[],
        String strTitle, final Activity activity) {

    AlertDialog.Builder alertDialogBuilder =  
            new AlertDialog.Builder(activity);
    alertDialogBuilder.setTitle(strTitle);

    alertDialogBuilder.setItems(strArray,
            new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
           Toast.makeText(activity, strArray [which], Toast.LENGTH_SHORT).show();

           //rest of your implementation
        }
    });
   return alertDialogBuilder;
}
like image 187
A--C Avatar answered Jan 19 '26 20:01

A--C


in onClick() event use switch statement to write click method for each button.

    @Override
        public void onClick(DialogInterface dialogInterface, int arg) {
            // TODO Auto-generated method stub
            switch (arg) {
               case 0:
                  //you code for button at 0 index click
                  break;
               case 1:
                  //you code for button at 1 index click
                  break;
               default:
                    break;
            }
        }

Here, arg indicates the index of the button pressed. you can also access that button using strArray[arg]

like image 20
Akbari Dipali Avatar answered Jan 19 '26 21:01

Akbari Dipali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!