首页 > 解决方案 > Proguard - IllegalStateException:创建时不得附加 ViewHolder 视图

问题描述

在我的 gradle 文件中启用 minifyEnabled 后,应用程序继续崩溃。我已经搜索了很多,但我对 Proguard 感到不舒服,我不确定问题可能出在哪里。也许我需要在 proguard-rules pro 中添加更多保留?

构建.gradle

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

proguard-rules.pro

##---------------Begin: proguard configuration for Gson  ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-dontwarn sun.misc.**
#-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }

# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

##---------------End: proguard configuration for Gson  ----------

-keep class com.sterbsociety.** {*;}
-keep class package.model.* {*;}
-keep class androidx.recyclerview.widget.RecyclerView.** {*;}
-keepattributes *Annotation*,Signature, InnerClasses

错误:

java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)
        at androidx.recyclerview.widget.RecyclerView$a.createViewHolder(:6)
        at androidx.recyclerview.widget.RecyclerView$p.a(:60)
        at androidx.recyclerview.widget.RecyclerView$p.a(:26)
        at androidx.recyclerview.widget.RecyclerView$p.c(:2)

任何想法?提前致谢。

标签: androidandroid-recyclerviewproguard

解决方案


该错误可能与 proguard 无关,但与您如何为 ViewHolder 扩展布局有关。尝试确保您使用如下false参数膨胀布局:

  @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    Context context = viewGroup.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout, use false.
    View contactView = inflater.inflate(R.layout.item_of_yours, viewGroup, false);

    ...

    return viewHolder;
  }

推荐阅读