0

我有以下代码不起作用,我应该怎么做才能调试它?

我创建了一个新的 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]

顺便说一句,我还尝试了其他一些事情:DialogFragment doesn't show up

4

2 回答 2

3

从您的 layout.xml 中删除 android:onClick="Test" 并使用

Button btn = (Button) view.findViewById(R.id.your_btn);
btn.setOnClickListener(new OnClickListener() {
test();
});

反而

顺便提一句。你不应该使用 getApplicationContext() ---> 使用这个

于 2012-11-11T23:59:24.940 回答
1

那是一个独特的 LogCat,您手动重写了,不是吗... :) 下次您可以突出显示 LogCat 并按Ctrl+C

无论如何,我看到了 BadTokenException。改变:

new AlertDialog.Builder(this.getApplicationContext());

到:

new AlertDialog.Builder(MyActivity.this);
于 2012-11-11T23:51:01.187 回答