findViewById中未发出的ClassCastException

时间:2016-08-19 12:45:21

标签: java android classcastexception

我在xml文件中有以下代码:

<android.support.v7.widget.GridLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id = "@+id/buttonsLayout"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:layout_gravity = "center"
     app:columnCount="4"
     app:rowCount="4"
     app:useDefaultMargins="false"
     >
</android.support.v7.widget.GridLayout>

我正在动态填充这个GridLayout,所以我试图通过以下方式填充对象:

android.support.v7.widget.GridLayout gl = 
    (android.support.v7.widget.GridLayout)findViewById(R.id.buttonsLayout);

这给了我以下错误:

Caused by: java.lang.ClassCastException: android.support.v7.internal.widget.TintButton cannot be cast to android.support.v7.widget.GridLayout at com.education4all.mathcoach.TaskActivity.onCreate(TaskActivity.java:134)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104) 
at android.app.ActivityThread.access$600(ActivityThread.java:132) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4575) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 
at dalvik.system.NativeStart.main(Native Method)

这很奇怪,因为此代码曾经工作,突然出现此错误。为什么会这样?

build_gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion '21.1.2'
    defaultConfig {
        applicationId "com.education4all.mathcoach"
        minSdkVersion 10
        targetSdkVersion 22
        versionName '1.0.2'
        versionCode 4
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support:gridlayout-v7:18.0.+'
}

1 个答案:

答案 0 :(得分:0)

尝试使用更高版本的支持库,即:com.android.support:appcompat-v7:22.+,清理并尝试运行该项目。

您也可以使用最新版本的GridLayout。