单击按钮时打开对话框

men*_*top 19 android dialog

我有一个按钮,我想在按下时打开一个对话框.这是我的代码:

Button more = (Button) findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        //Intent myIntent = new Intent(view.getContext(), agones.class);
        //startActivityForResult(myIntent, 0);

        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("hi");
        alertDialog.setMessage("this is my app");

        alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // here you can add functions
        }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

Ama*_*lam 38

正如@Roflcoptr所说,你还没有调用alertDialog.show()方法.因此您的对话框不会出现.

这是您编辑的代码:

Button more = (Button) findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        //Intent myIntent = new Intent(view.getContext(), agones.class);
        //startActivityForResult(myIntent, 0);


        AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
        alertDialog.setTitle("hi");
        alertDialog.setMessage("this is my app");

        alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
              // here you can add functions
           }
        });

        alertDialog.show();  //<-- See This!
    }

});
Run Code Online (Sandbox Code Playgroud)

如果你写this而不是<ActivityName>.this,那么它将采用引用,View.OnClickListener因为this当前正在其中访问.您需要在那里提供您的活动名称.

  • 而创造只是不给,因为这给了myActivity.this .......它会工作. (3认同)

Rof*_*ion 11

您的对话框未显示,因为您没有调用AlertDialog #show.