最近在写一个Android的library module,打算在库项目里面写一个自定义控件。

自定义控件里面有自己特有的属性。在attr.xml里面生成自己的自定义属性。

代码如下:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3. <attrname="top_icon"format="reference"/>
  4. <attrname="bottom_icon"format="reference"/>
  5. <declare-styleablename="GradientIconView">
  6. <attrname="top_icon"/>
  7. <attrname="bottom_icon"/>
  8. </declare-styleable>
  9. <attrname="text"format="string"/>
  10. <attrname="text_size"format="dimension"/>
  11. <attrname="top_text_color"format="color"/>
  12. <attrname="bottom_text_color"format="color"/>
  13. <declare-styleablename="GradientTextView">
  14. <attrname="text"/>
  15. <attrname="text_size"/>
  16. <attrname="top_text_color"/>
  17. <attrname="bottom_text_color"/>
  18. </declare-styleable>
  19. </resources>


但是在代码里面使用这些属性的时候却报错了。

[java] view plain copy
  1. TypedArraya=context.obtainStyledAttributes(attrs,
  2. R.styleable.GradientIconView);
  3. BitmapDrawabledrawable;
  4. intn=a.getIndexCount();
  5. for(inti=0;i<n;i++){
  6. intattr=a.getIndex(i);
  7. switch(attr){
  8. caseR.styleable.GradientIconView_top_icon:
  9. drawable=(BitmapDrawable)a.getDrawable(attr);
  10. setTopIconView(drawable);
  11. break;
  12. caseR.styleable.GradientIconView_bottom_icon:
  13. drawable=(BitmapDrawable)a.getDrawable(attr);
  14. setBottomIconView(drawable);
  15. break;
  16. }
  17. }

错误的内容主要是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报错可能就是我遇到的这个问题。

更多相关文章

  1. Cause: android-apt plugin is incompatible with the Android(
  2. Android(安卓)UI学习 - Tab的学习和使用
  3. Android(安卓)软键盘遮挡问题
  4. Android编译问题:Only 64-bit build environments are supported
  5. android:configChanges属性总结
  6. Android开发EditText属性
  7. Android(安卓)Linux Socket 数据传输错误
  8. android开发 使用uses-sdk 导致布局不一样解决
  9. Android(安卓)UI学习 - Tab的学习和使用

随机推荐

  1. 【Android(安卓)Developers Training】 6
  2. 谷歌CTS测试之GTS测试简介
  3. Android(安卓)如何添加一种锁屏方式
  4. MTK Android(安卓)P 开机无动画,无铃声问
  5. Unity2018下Android(安卓)SDK设置
  6. Android(安卓)解析Json
  7. Android(安卓)Studio之项目突然出现乱码
  8. Android(安卓)开发技术周报 Issue#290
  9. android 动态注册JNI函数过程源码分析
  10. Android(安卓)Studio如何导入第三方库进