首页 > 解决方案 > Horizo​​ntalScrollView 正在崩溃 onRestoreInstance

问题描述

从更改 Horizo​​ntalScrollView 的高度后

<HorizontalScrollView
                android:id="@+id/topics_scroll_view"
                android:layout_width="match_parent"
                android:layout_height="92dp"/>

<HorizontalScrollView
                android:id="@+id/topics_scroll_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

我开始崩溃了

Caused by java.lang.ClassCastException
              android.view.AbsSavedState$1 cannot be cast to android.widget.HorizontalScrollView$SavedState
              android.widget.HorizontalScrollView.onRestoreInstanceState (HorizontalScrollView.java:1678)

崩溃发生在 Horizo​​ntalScrollView 中的这个方法上

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        // Some old apps reused IDs in ways they shouldn't have.
        // Don't break them, but they don't get scroll state restoration.
        super.onRestoreInstanceState(state);
        return;
    }
    SavedState ss = (SavedState) state;       //*******this line is crashing
    super.onRestoreInstanceState(ss.getSuperState());
    mSavedState = ss;
    requestLayout();
}

我发现了一个类似的问题,我怀疑混淆没有保持 Parcelable,他们建议将其添加到 proguard 文件中

-keepclassmembers class * implements android.os.Parcelable {
static ** CREATOR;
}

当我查看我的 proguard 文件时,我发现我已经包含了以下内容

-keepnames class * implements android.os.Parcelable { *; }
-keepclassmembers class * implements android.os.Parcelable { *; }

任何人都可以区分问题以及为什么当我更改时它现在开始崩溃android:layout_height?这对任何人都有意义吗?提前致谢

编辑:在阅读了一些类似的问题后,我发现这个java.lang.ClassCastException: android.view.AbsSavedState$1 can be cast to android.support.v7.widget.Toolbar$SavedState
now if you read the answer it says that using same android:idfor不同的视图可能会导致这种情况,所以我注意到我最近添加了一个视图,该视图包含在与 Horizo​​ntalScrollView 相同的布局中,并且视图包含这个

<RelativeLayout
            android:id="@+id/topics_scroll_view"
            android:layout_width="match_parent"
            android:layout_height="92dp"/>

这可能是问题吗?

标签: androidclasscastexceptionhorizontalscrollview

解决方案


是的,这绝对是因为您对两个布局使用了相同的 id。

首先,交叉检查您的应用程序是否没有在两个不同的地方重用相同的 ID。

onRestoreInstanceState已经执行了该方法findViewById并且找到的第一个视图不是Horizo​​ntalScrollView。


推荐阅读