我有以下代码不起作用,我该怎么做才能调试它?
我创建了一个新的android 2.2项目,添加了一个按钮,按钮有:
android:onClick="Test"
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();
}
当它被触发时,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我还尝试了其他一些事情:DialogFragment doesn't show up
答案 0 :(得分:3)
从layout.xml中删除android:onClick =“Test”并使用
Button btn = (Button) view.findViewById(R.id.your_btn);
btn.setOnClickListener(new OnClickListener() {
test();
});
而不是
顺便说一句。你不应该使用getApplicationContext()---&gt;使用这个
答案 1 :(得分:1)
这是一个独特的LogCat,你重写了手工没有你... :)下次你可以突出显示LogCat并按 Ctrl + C < / p>
无论如何,我看到了BadTokenException。变化:
new AlertDialog.Builder(this.getApplicationContext());
要:
new AlertDialog.Builder(MyActivity.this);