API 19下SeekBar加载崩溃求助(InflateException异常)
解决API 19设备中SeekBar加载自定义Vector Thumb导致的InflateException问题
我之前也碰到过一模一样的坑!本质原因是API 19及更低版本的系统本身不支持VectorDrawable,虽然AppCompat库做了兼容,但直接在layer-list这类Drawable资源里引用vector作为SeekBar的thumb,低版本系统的LayoutInflater在解析XML时,还是无法正确识别并加载vector资源,最终触发Inflate异常。
具体解决方案
方案1:改用AppCompatSeekBar并配置Vector兼容(最推荐)
这个方案改动最小,利用AppCompat的兼容能力解决问题:
- 替换布局中的原生SeekBar为AppCompatSeekBar:
<androidx.appcompat.widget.AppCompatSeekBar android:id="@+id/seekBarSpeedSet" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@drawable/corner_fillet_background" android:max="200" android:progress="0" android:thumb="@drawable/icon_seek_thumb" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tvSpeedSet" />
如果你的项目还在用旧的android.support库,就用android.support.v7.widget.AppCompatSeekBar替代。
- 确保页面Activity继承自AppCompatActivity:
public class HomePage extends AppCompatActivity { // ... 你的业务代码 }
- 在app模块的build.gradle中开启Vector兼容配置:
android { defaultConfig { vectorDrawables.useSupportLibrary = true } }
方案2:代码中手动加载Vector并设置Thumb
如果方案1仍有兼容问题,可以通过代码绕开XML解析的限制:
首先给icon_seek_thumb.xml里的Vector item添加一个id:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape> <size android:height="40dp" android:width="40dp" /> <solid android:color="@android:color/transparent" /> </shape> </item> <item android:id="@+id/vector_thumb_layer" android:drawable="@drawable/ic_seek_thumb"/> </layer-list>
然后在Activity中手动加载Vector并替换LayerDrawable里的对应项:
SeekBar seekBar = findViewById(R.id.seekBarSpeedSet); // 用VectorDrawableCompat兼容加载矢量图 Drawable vectorThumb = VectorDrawableCompat.create(getResources(), R.drawable.ic_seek_thumb, getTheme()); // 获取原来的layer-list资源 LayerDrawable layerThumb = (LayerDrawable) getResources().getDrawable(R.drawable.icon_seek_thumb); // 替换其中的矢量图项 layerThumb.setDrawableByLayerId(R.id.vector_thumb_layer, vectorThumb); // 设置给SeekBar seekBar.setThumb(layerThumb);
方案3:降级为PNG资源(不推荐)
把ic_seek_thumb.xml转成不同分辨率的PNG图片,放到drawable-xxhdpi、drawable-xhdpi等对应目录下,然后修改icon_seek_thumb.xml引用PNG资源。这种方法虽然能解决问题,但需要维护多份图片资源,后期迭代成本高。
验证
做完以上修改后,API 19设备上的SeekBar应该能正常加载,不会再抛出InflateException了。
内容的提问来源于stack exchange,提问作者Ravi Belkhindi
相关产品推荐
相关产品推荐

