Android: reduce the code for handling alertdialog

I'm new to Java development... I'm trying to implement alert in Android applications using the following code

        AlertDialog.Builder alert=new AlertDialog.Builder(this);
        alert.setMessage("I'm a multi-button alert :-)");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), 
                    "OK",
                    Toast.LENGTH_LONG)
                    .show();
            }
        });
        alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), 
                    "KO",
                    Toast.LENGTH_LONG)
                    .show();
            }
        });
        alert.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), 
                    "CANCEL",
                    Toast.LENGTH_LONG)
                    .show();
            }
        });
        alert.show();

It runs, but I want to avoid, for each button, the new dialoginterface. Onclicklistener... By pointing to a single function that handles clicking the button. I think it's possible, but I don't know how, can anyone help me?

Thank you in advance C

resolvent:

You can implement dialoginterface.onclicklistener in the containing class and monitor the parameters to view and which button to click

alert.setPositiveButton("Ok", this);
alert.setNegativeButton("No", this);
alert.setNeutralButton("Cancel", this);

public void onClick(DialogInterface dialog, int which) {
    String text = "";

    switch (which)
    {
        case DialogInterface.BUTTON_NEGATIVE:
            text = "Cancel";
    }

    Toast.makeText(getApplicationContext(), 
        text,
        Toast.LENGTH_LONG)
        .show();
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>