Usage of setPositiveButton() and setNegativeButton()

The methods setPositiveButton() and setNegativeButton() are used in the AlertDialog.Builder class to set the text and click events for the “positive” and “negative” buttons in the dialog.

Here is how to use setPositiveButton():

  1. Call the setPositiveButton() method on the AlertDialog.Builder object.
  2. Pass in two parameters: the text string of the button and the button’s click event listener.
  3. The text string of the button can either be a reference to a string resource or a direct string.
  4. The button’s onClick listener can be an object that implements the DialogInterface.OnClickListener interface, or it can be an anonymous inner class.

The sample code is shown below:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        // 在这里处理"确定"按钮的点击事件
    }
});

The usage of setNegativeButton() is similar to setPositiveButton(), but the button’s text and click event are different.

The sample code is shown below:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        // 在这里处理"取消"按钮的点击事件
    }
});

Note: Both the setPositiveButton() and setNegativeButton() methods can be used together to set two buttons in the dialog box.

Leave a Reply 0

Your email address will not be published. Required fields are marked *