在Android代码中显示吐司时,我收到以下错误:java.lang.RuntimeException:setView必须已被调用

时间:2014-12-07 10:00:42

标签: android-toast

我正在使用的代码:

Toast t = new Toast(this);
t.makeText(this, "You clicked the button..", Toast.LENGTH_SHORT);
t.show();

[我知道我可以使用:

Toast t = Toast.makeText(this, "You clicked the button..", Toast.LENGTH_SHORT);
t.show()

但我想知道顶部代码段的问题

详细错误日志:

12-07 15:09:58.333: E/AndroidRuntime(16159): FATAL EXCEPTION: main
12-07 15:09:58.333: E/AndroidRuntime(16159): java.lang.IllegalStateException: Could not execute method of the activity
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.view.View$1.onClick(View.java:3838)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.view.View.performClick(View.java:4475)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.view.View$PerformClick.run(View.java:18786)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.os.Handler.handleCallback(Handler.java:730)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.os.Looper.loop(Looper.java:176)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.app.ActivityThread.main(ActivityThread.java:5419)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at java.lang.reflect.Method.invokeNative(Native Method)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at java.lang.reflect.Method.invoke(Method.java:525)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at dalvik.system.NativeStart.main(Native Method)
12-07 15:09:58.333: E/AndroidRuntime(16159): Caused by: java.lang.reflect.InvocationTargetException
12-07 15:09:58.333: E/AndroidRuntime(16159):    at java.lang.reflect.Method.invokeNative(Native Method)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at java.lang.reflect.Method.invoke(Method.java:525)
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.view.View$1.onClick(View.java:3833)
12-07 15:09:58.333: E/AndroidRuntime(16159):    ... 11 more
12-07 15:09:58.333: E/AndroidRuntime(16159): Caused by: java.lang.RuntimeException: setView must have been called
12-07 15:09:58.333: E/AndroidRuntime(16159):    at android.widget.Toast.show(Toast.java:114)

1 个答案:

答案 0 :(得分:1)

嗯,您使用的那个不是建议的方法。显然构造函数是公共的,但不应该以这种方式使用它。

调用静态方法makeText的代码段实际上不会更改Toast对象t

但是在Toast中t = Toast.makeText(...);例如,Toast t是Toast.makeText的返回值