如何通过单击按钮获得简单警报?

时间:2012-01-17 16:42:17

标签: android android-dialog

我正在玩一个简单的应用程序,我想在点击按钮时显示警告。

我到目前为止的代码是:

package max.helloworld.firstapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */

private Button closeButton;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    this.setContentView(R.layout.main);
    this.closeButton = (Button)this.findViewById(R.id.close);
    this.closeButton.setKeyListener(new onClickListener() {
        @Override
        public void onClick(View v) { 
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();               
            alertDialog.setTitle("Transformers");
            alertDialog.setMessage("Optimus Prime");
            alertDialog.setButton("OK", new OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                }
            });
            //alertDialog.setIcon(R.drawable.icon);
            alertDialog.show();
            finish();
        }
    }); 
}
}

问题在于它说AlertDialog alertDialog = new AlertDialog.Builder(this).create();

它说构造函数是未定义的。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

更改此行:

`AlertDialog alertDialog = new AlertDialog.Builder(this).create();`

要:

`AlertDialog alertDialog = new AlertDialog.Builder(yourActivityName.this);`

答案 1 :(得分:2)

关键字this解析为该范围内OnClickListener的实例。要返回您的活动实例,请将this替换为HelloWorldActivity.this