现在的位置: 首页 > 移动开发 > 正文

Android布局中的ClassCastException

2019年06月03日 移动开发 ⁄ 共 1914字 ⁄ 字号 评论关闭

ClassCastException,从字面上看,是类型转换错误,通常是进行强制类型转换时候出的错误。但是在布局中出现的ClassCastException的比较少见,甚至找不到哪里有类型转换。

一、先介绍什么是ClassCastException

nimal表示动物,Dog表示狗,是动物的子类,Cat表示猫,是动物的子类。看下面的代码:
Animal a1 = new Dog();  // 1
Animal a2 = new Cat();  // 2
 
Dog d1 = (Dog)a1;         //3
Dog d2 = (Dog)a2;        //4
第3行代码和第4行代码基本相同,从字面意思看都是把动物(Animal)强制转换为狗(Dog),但是第4行代码将产生java.lang.ClassCastException。原因是你要把一个猫(a2这只动物是猫)转换成狗,而第3行中是把狗转换成狗,所以可以。

从上面的例子看,java.lang.ClassCastException是进行强制类型转换的时候产生的异常,强制类型转换的前提是父类引用指向的对象的类型是子类的时候才可以进行强制类型转换,如果父类引用指向的对象的类型不是子类的时候将产生java.lang.ClassCastException异常。就是上面a1和a2都是动物,但是a1这只动物是一只狗,而a2这只动物是猫,所以要把a1转换成狗可以,因为a1本身就是狗,而a2是一只猫,所以要转换成狗就出错了。
遇到这样的异常的时候如何解决呢?如果你知道要访问的的对象的具体类型,直接转换成该类型即可。如果不能确定类型可以通过下面的两种方式进行处理(假设对象为o):
1、通过o.getClass().getName()得到具体的类型,可以通过输出语句输出这个类型,然后根据类型进行进行具体的处理。
2、通过if(o instanceof 类型)的语句来判断o的类型是什么。
二、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。

抱歉!评论已关闭.