您的位置:首页 > 移动开发 > Android开发

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

2016-03-02 10:24 579 查看
最近在写一个Android的library module,打算在库项目里面写一个自定义控件。

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

代码如下:

[html] view
plain copy

<?xml version="1.0" encoding="utf-8"?>  

<resources>  

    <attr name="top_icon" format="reference" />  

    <attr name="bottom_icon" format="reference" />  

  

    <declare-styleable name="GradientIconView">  

        <attr name="top_icon" />  

        <attr name="bottom_icon" />  

    </declare-styleable>  

  

    <attr name="text" format="string" />  

    <attr name="text_size" format="dimension" />  

    <attr name="top_text_color" format="color" />  

    <attr name="bottom_text_color" format="color" />  

  

    <declare-styleable name="GradientTextView">  

        <attr name="text" />  

        <attr name="text_size" />  

        <attr name="top_text_color" />  

        <attr name="bottom_text_color" />  

    </declare-styleable>  

</resources>  

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

[java] view
plain copy

TypedArray a = context.obtainStyledAttributes(attrs,  

            R.styleable.GradientIconView);  

  

    BitmapDrawable drawable;  

  

    int n = a.getIndexCount();  

    for (int i = 0; i < n; i++) {  

  

        int attr = a.getIndex(i);  

        switch (attr) {  

            case R.styleable.GradientIconView_top_icon:  

                drawable = (BitmapDrawable) a.getDrawable(attr);  

                setTopIconView(drawable);  

                break;  

            case R.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报错可能就是我遇到的这个问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android Studio Modul