我是android developpement的新手,在尝试创建可编辑的TextView时遇到了以下异常。
以下是异常的完整堆栈跟踪
09-17 01:25:14.749: E/AndroidRuntime(8436): FATAL EXCEPTION: main
09-17 01:25:14.749: E/AndroidRuntime(8436): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.timer/com.example.timer.TimerHomeActivity}: java.lang.ClassCastException: android.widget.TextView
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.os.Looper.loop(Looper.java:130)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.ActivityThread.main(ActivityThread.java:3687)
09-17 01:25:14.749: E/AndroidRuntime(8436): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 01:25:14.749: E/AndroidRuntime(8436): at java.lang.reflect.Method.invoke(Method.java:507)
09-17 01:25:14.749: E/AndroidRuntime(8436): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
09-17 01:25:14.749: E/AndroidRuntime(8436): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
09-17 01:25:14.749: E/AndroidRuntime(8436): at dalvik.system.NativeStart.main(Native Method)
09-17 01:25:14.749: E/AndroidRuntime(8436): Caused by: java.lang.ClassCastException: android.widget.TextView
09-17 01:25:14.749: E/AndroidRuntime(8436): at com.example.timer.TimerHomeActivity.onCreate(TimerHomeActivity.java:23)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-17 01:25:14.749: E/AndroidRuntime(8436): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
09-17 01:25:14.749: E/AndroidRuntime(8436): ... 11 more
这是代码:
public class TimerHomeActivity extends Activity implements OnClickListener {
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.timer_1);
tv.setText("Hi");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_home);
Button timer1 = (Button)findViewById(R.id.timer_1);
timer1.setOnClickListener(this);
}
}
答案 0 :(得分:3)
检查您的资源ID。您将两次加载相同的资源ID,一次转换为TextView
,一次转换为Button
:
TextView tv = (TextView)findViewById(R.id.timer_1);
和
Button timer1 = (Button)findViewById(R.id.timer_1);
它应该对应一个小部件而另一个小部件会抛出ClassCastException
。
由于启动活动时发生异常,导致异常的语句应该是onCreate
方法中的语句。这意味着资源timer_1
不是Button
而是TextView
(如异常消息中所示,顺便说一句,这似乎会在您的帖子中被截断)。