ClassCastException,从字面上看,是类型转换错误,通常是进行强制类型转换时候出的错误。但是在布局中出现的ClassCastException的比较少见,甚至找不到哪里有类型转换。
一、先介绍什么是ClassCastException。
二、Android布局文件中存在的类型转换是由于当组件由于长宽的设置导致一个组件覆盖另一个组件,这是在底层的处理正是将被覆盖的组件转化成另一个组件的类型。当然当两个组件非父子关系时,会出现ClassCastException。
如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:text="上下左右控制虫子方向"
android:textSize="20sp" />
<com.study.mysnake.view.MainView
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:id="@+id/main_view">
</com.study.mysnake.view.MainView>
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:text="开始" />
<Button
android:id="@+id/end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:text="结束" />
</LinearLayout>
MainView组件由于wrap_content将button组件覆盖,解决方法:
将layout_heigh的值设为200dp。