Android(安卓)Studio module里面放switch语句报错 R文件找不到
16lz
2022-01-11
最近在写一个Android的library module,打算在库项目里面写一个自定义控件。
自定义控件里面有自己特有的属性。在attr.xml里面生成自己的自定义属性。
代码如下:
[html] view plain copy
- <?xmlversion="1.0"encoding="utf-8"?>
- <resources>
- <attrname="top_icon"format="reference"/>
- <attrname="bottom_icon"format="reference"/>
- <declare-styleablename="GradientIconView">
- <attrname="top_icon"/>
- <attrname="bottom_icon"/>
- </declare-styleable>
- <attrname="text"format="string"/>
- <attrname="text_size"format="dimension"/>
- <attrname="top_text_color"format="color"/>
- <attrname="bottom_text_color"format="color"/>
- <declare-styleablename="GradientTextView">
- <attrname="text"/>
- <attrname="text_size"/>
- <attrname="top_text_color"/>
- <attrname="bottom_text_color"/>
- </declare-styleable>
- </resources>
但是在代码里面使用这些属性的时候却报错了。
[java] view plain copy
- TypedArraya=context.obtainStyledAttributes(attrs,
- R.styleable.GradientIconView);
- BitmapDrawabledrawable;
- intn=a.getIndexCount();
- for(inti=0;i<n;i++){
- intattr=a.getIndex(i);
- switch(attr){
- caseR.styleable.GradientIconView_top_icon:
- drawable=(BitmapDrawable)a.getDrawable(attr);
- setTopIconView(drawable);
- break;
- caseR.styleable.GradientIconView_bottom_icon:
- drawable=(BitmapDrawable)a.getDrawable(attr);
- setBottomIconView(drawable);
- break;
- }
- }
错误的内容主要是case R.styleable.***这两句报错,一开始我还以为是library module的R文件没有生成。
又是clean project又是rebuild project.都没用。后来我发现TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GradientIconView);
这句没有报错,原来是我把问题定位错了,问题不是R文件没有生成,而是case R.styleable.***这句有问题。
看到错误提示如下:
这时候才恍然大悟,Resource IDs这一类的变量在API14之后的库项目里是不能在switch case statement里面使用的。
也就是说这时候只要把switch case的写法换成if else的写法就可以避免这样的错误。详情于解决方法可见。
最后再次总结一下,AndroidStudio是个新的开发工具,有很多种情况会导致R.java文件报错。
关键在于定位到问题出在哪里?像在库项目里面R.styleable报错可能就是我遇到的这个问题。
更多相关文章
- Cause: android-apt plugin is incompatible with the Android(
- Android(安卓)UI学习 - Tab的学习和使用
- Android(安卓)软键盘遮挡问题
- Android编译问题:Only 64-bit build environments are supported
- android:configChanges属性总结
- Android开发EditText属性
- Android(安卓)Linux Socket 数据传输错误
- android开发 使用uses-sdk 导致布局不一样解决
- Android(安卓)UI学习 - Tab的学习和使用