我正在尝试创建一个对话框,该对话框将显示何时单击图像但我的代码似乎存在一些问题。代码如下所示。我已完成对话框的导入,但它似乎不起作用,因为启动新对话框时出错。
ImageButton ib = (ImageButton)findViewById(R.id.imageButton1);
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog ad = new AlertDialog.Builder(this)
.setMessage("Blah blah blah.\n Fine pring.\n Do you accept all our terms and conditions?")
.setIcon(R.drawable.ic_launcher)
.setTitle("Terms of Service")
.setNeutralButton("back", this)
.setCancelable(false)
.create();
ad.show();
}
});
答案 0 :(得分:0)
问题是你在行上this
的引用
AlertDialog ad = new AlertDialog.builder(this)
实际上指的是不扩展Context的匿名内部类View.OnClickListener
。所以,就在你的
ib.setOnClickListener(new View.OnClickListener() {
将某些内容付诸实施
final Context context = this;
然后将上述构建器调用更改为
AlertDialog ad = new AlertDialog.builder(context)
即
ImageButton ib = (ImageButton)findViewById(R.id.imageButton1);
final Context context = this;
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog ad = new AlertDialog.Builder(context)
.setMessage("Blah blah blah.\n Fine pring.\n Do you accept all our terms and conditions?")
.setIcon(R.drawable.ic_launcher)
.setTitle("Terms of Service")
.setNeutralButton("back", this)
.setCancelable(false)
.create();
ad.show();
}
});
我正在做出(也许是崇高的)假设,即该代码块确实存在于实际扩展Context的类中。