[英]How to pop up an Android dialog
I have the following code which doesn't work, what should I do to debug it? 我有以下无效的代码,该如何调试?
I created a new android 2.2 project, added a button and the button has: 我创建了一个新的android 2.2项目,添加了一个按钮,该按钮具有:
android:onClick="Test"
the Test()
function is here: Test()
函数在这里:
public void Test(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this.getApplicationContext());
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("ok", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1)
{
// TODO Auto-generated method stub
arg0.dismiss();
}});
builder.setCancelable(false);
builder.create().show();
}
When it's triggered, the show()
will cause this exception: 触发时,
show()
会导致此异常:
Thread [<1> main] (Suspended (exception WindowManager$BadTokenException))
<VM does not provide monitor information>
AlertDialog(Dialog).show() line: 245
MainActivity.Test(View) line: 39
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
View$1.onClick(View) line: 2067
Button(View).performClick() line: 2408
View$PerformClick.run() line: 8817
ViewRoot(Handler).handleCallback(Message) line: 587
ViewRoot(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 143
ActivityThread.main(String[]) line: 4914
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 868
ZygoteInit.main(String[]) line: 626
NativeStart.main(String[]) line: not available [native method]
BTW There are some other things I tried: DialogFragment doesn't show up 顺便说一句,我尝试了其他一些操作: DialogFragment不显示
remove android:onClick="Test" from your layout.xml and use 从您的layout.xml中删除android:onClick =“ Test”并使用
Button btn = (Button) view.findViewById(R.id.your_btn);
btn.setOnClickListener(new OnClickListener() {
test();
});
instead 代替
btw. 顺便说一句。 you should't use getApplicationContext() ---> use this
你不应该使用getApplicationContext()--->使用它
That is a unique LogCat, you rewrote that by hand didn't you... :) Next time you can highlight the LogCat and press Ctrl + C 那是一个独特的LogCat,您手动改写了,不是... :)下次您可以突出显示LogCat并按Ctrl + C
Anyway, I see the BadTokenException. 无论如何,我看到了BadTokenException。 Change:
更改:
new AlertDialog.Builder(this.getApplicationContext());
To: 至:
new AlertDialog.Builder(MyActivity.this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.