最近在寫一個Android的library module,打算在庫項目裏面寫一個自定義控件。
自定義控件裏面有自己特有的屬性。在attr.xml裏面生成自己的自定義屬性。
代碼如下:
<?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>
但是在代碼裏面使用這些屬性的時候卻報錯了。
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報錯可能就是我遇到的這個問題。