3

我刚开始学习Android,这是我的java文件的代码。我没有更改 XML 文件。运行此代码时,会显示简单的空白活动,没有对话框。需要帮助。

package com.example.dialogbox;

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

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Add("Exit App", "Are u sure?");
    Toast.makeText(this, "open", Toast.LENGTH_LONG);
}

public void Add(String title, String msg) {
    Toast.makeText(this, "open", Toast.LENGTH_LONG);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title)
            .setMessage(msg)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            // TODO Auto-generated method stub

                        }
                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });
    AlertDialog alert = builder.create();

}

}  
4

1 回答 1

2

您忘记调用show()方法。添加alert.show(),您的Add()方法将如下所示:

public void Add(String title, String msg) {

    System.out.println("heyo");
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title)
            .setMessage(msg)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            // TODO Auto-generated method stub

                        }
                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });
    AlertDialog alert = builder.create();
    alert.show()

}
于 2012-08-05T09:33:22.167 回答