Android Studio module里面放switch语句报错 R文件找不到

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

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

代码如下:

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


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

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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值