美文网首页程序员Android开发开发笔记
Error inflating class CheckBox(背

Error inflating class CheckBox(背

作者: Android小马哥 | 来源:发表于2018-05-23 20:23 被阅读12次

    出现原因

    Checkbox要加个按钮,公司UI给的背景图是SVG格式的。
    然后给checkbox设置background的时候,因为背景drawable的xml文件是vector(svg)的。在4.x版本的手机就报这个错了。5.0以上是没问题的。

    解决方式

    不在布局文件中设置背景。改为在代码中设置。
    因为这个问题之前发生过,公司小伙伴给了我个Util类,l里面做的事情就是把vectorDrawable转化到了StateListDrawable里面,这几个类都是谷歌android包下的,具体还没研究。其中对应的方法如下。

     /** 设置使用Vector做selector,作为view的背景 */
        public static void setVectorSelectorBackground(Context context, View view, @DrawableRes int normalVectorId,
                @DrawableRes int pressedVectorId) {
            setViewBackground(view, getSelector(context, normalVectorId, pressedVectorId));
        }
    
      @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public static void setViewBackground(View view, Drawable background) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                view.setBackground(background);
            } else {
                view.setBackgroundDrawable(background);
            }
        }
    /** 获取Vector组成的selector */
        public static StateListDrawable getSelector(Context context, @DrawableRes int normalVectorId,
                @DrawableRes int pressedVectorId) {
            VectorDrawableCompat normalVector = VectorDrawableCompat
                    .create(context.getResources(), normalVectorId, context.getTheme());
            VectorDrawableCompat pressedVector = VectorDrawableCompat
                    .create(context.getResources(), pressedVectorId, context.getTheme());
            StateListDrawable stateListDrawable = new StateListDrawable();
            if (pressedVector != null) {
                stateListDrawable.addState(new int[]{android.R.attr.state_selected}, pressedVector);
                stateListDrawable.addState(new int[]{android.R.attr.state_focused}, pressedVector);
                stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedVector);
                stateListDrawable.addState(new int[]{android.R.attr.state_checked}, pressedVector);
            }
            if (normalVector != null) {
                stateListDrawable.addState(new int[]{}, normalVector);
            }
            return stateListDrawable;
        }
    

    使用

    使用的话就跟就根据参数,把对应的选中(按压等)跟未选中的drawable传进来就可以

    ViewUtil.setVectorSelectorBackground(mContext,checkBox,R.drawable.svg_cb_unchecked,
                    R.drawable.svg_cb_checked);
    

    总结

    自从上一次创建微信公众号,创建简书账号,并在里面写文章。已经过去七八个月了。实在是惭愧。看周围很多同事都有记笔记的习惯。有的是写在CSDN,有的是记录在一些记笔记的软件上自己看查阅。自己之前代码写的也少,记录更是没有。希望以后下班的时候抽一点时间把开发中遇到的bug或者小总结记录一下。希望能帮到遇到同样问题的人,或者自己的方法可能有问题,别人看到了可以指出来。主要是做个记录吧。

    相关文章

      网友评论

        本文标题:Error inflating class CheckBox(背

        本文链接:https://www.haomeiwen.com/subject/vrddjftx.html