我试图在单击时获取TextView的整数值。为此,我使用XML文件的onClick属性。 这是我的XML代码:
<TextView
android:id="@+id/o1"
android:layout_width="wrap_content"
android:onClick="check"
android:layout_height="wrap_content" />
以下是检查方法:
public void check(View v) {
TextView c= (TextView) v;
int z = Integer.parseInt(c.getText().toString());
// more code here
这是堆栈跟踪:
10-30 20:16:47.952: E/AndroidRuntime(12427): java.lang.IllegalStateException: Could not execute method for android:onClick
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.view.View$DeclaredOnClickListener.onClick(View.java:4452)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.view.View.performClick(View.java:5198)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.view.View$PerformClick.run(View.java:21147)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.os.Handler.handleCallback(Handler.java:739)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.os.Handler.dispatchMessage(Handler.java:95)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.os.Looper.loop(Looper.java:148)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.app.ActivityThread.main(ActivityThread.java:5417)
10-30 20:16:47.952: E/AndroidRuntime(12427): at java.lang.reflect.Method.invoke(Native Method)
10-30 20:16:47.952: E/AndroidRuntime(12427): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-30 20:16:47.952: E/AndroidRuntime(12427): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-30 20:16:47.952: E/AndroidRuntime(12427): Caused by: java.lang.reflect.InvocationTargetException
10-30 20:16:47.952: E/AndroidRuntime(12427): at java.lang.reflect.Method.invoke(Native Method)
10-30 20:16:47.952: E/AndroidRuntime(12427): at android.view.View$DeclaredOnClickListener.onClick(View.java:4447)
10-30 20:16:47.952: E/AndroidRuntime(12427): ... 9 more
10-30 20:16:47.952: E/AndroidRuntime(12427): Caused by: java.lang.NumberFormatException: Invalid int: "518 "
10-30 20:16:47.952: E/AndroidRuntime(12427): at java.lang.Integer.invalidInt(Integer.java:138)
10-30 20:16:47.952: E/AndroidRuntime(12427): at java.lang.Integer.parse(Integer.java:410)
10-30 20:16:47.952: E/AndroidRuntime(12427): at java.lang.Integer.parseInt(Integer.java:367)
10-30 20:16:47.952: E/AndroidRuntime(12427): at java.lang.Integer.parseInt(Integer.java:334)
10-30 20:16:47.952: E/AndroidRuntime(12427): at com.project.project.MainActivity.check(MainActivity.java:69)
10-30 20:16:47.952: E/AndroidRuntime(12427): ... 11 more
任何帮助将不胜感激!
答案 0 :(得分:4)
Invalid int: "518 "
包含空格。在致电trim()
parseInt()
int z = Integer.parseInt(c.getText().toString().trim());