如何在我的应用程序中单击“确定”按钮时显示AlertDialog?

时间:2015-01-19 06:22:28

标签: android

我在“警报对话框”下方使用以显示消息。

我想仅在用户点击" OK"时才显示此警报对话框。按钮。

我该怎么做?

/* Show Warning Dialog begins */
builder = new AlertDialog.Builder(this);

// Creates textview for centre title
myMsg = new TextView(this);
myMsg.setText("Hello");
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
myMsg.setTextSize(20); 
myMsg.setTextColor(Color.WHITE);

//set custom title
builder.setCustomTitle(myMsg);
builder.setMessage("Hi!");
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();

//Create custom message
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
/* Show Warning Dialog ends */

2 个答案:

答案 0 :(得分:1)

你可以简单地使用它。您需要为按钮实现DialogInterface.OnClickListener()界面。

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
    // do your stuff here
 }
});

答案 1 :(得分:0)

将click Listener添加到您的正面按钮,如下所示:

/*Show Warning Dialog*/
                    builder = new AlertDialog.Builder(this);
                    // Creates textview for centre title
                      myMsg = new TextView(this);
                      myMsg.setText("Hello");
                      myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
                      myMsg.setTextSize(20); 
                      myMsg.setTextColor(Color.WHITE);
                    //set custom title
                    builder.setCustomTitle(myMsg);
                    builder.setMessage("Hi!");
                    builder.setPositiveButton("OK", new                   DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
       // Execute your process
             }
            });  

              AlertDialog dialog = builder.show();
                    //Create custom message
                    TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
                    messageText.setGravity(Gravity.CENTER);
                    /*Show Warning Dialog ends*/