最近在封裝一些 自定義的View 遇到了一些 自定義attr 屬性的問題, 這裡來複習總結下:
1. 定義attire 屬性
在res/values 檔案下建立一個attrs.xml 裡面都是些 attr 屬性相關的檔案
在裡面可以自己 定義 屬性 如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
<declare-styleable name="MyImageView">
<attr name="imgSrc" format="reference"/>
</declare-styleable>
</resources>
上面的内容很容易了解, 需要注意的是 format 有以下幾種類型: 1.reference:參考某一資源ID( 圖檔資源之類的) 2. color:顔色值 3. boolean:布爾值 4. dimension:尺寸值 5. float:浮點值 6. integer:整型值 7. string:字元串 8. fraction:百分數 9. enum:枚舉值 10. flag:位或運算
具體的用法 更詳細的内容 可以參考這片文章, 這些 format都介紹的很詳細 http://blog.sina.com.cn/s/blog_62ef2f14010105vi.html
2. 使用自定義的 attr屬性 為了讓布局檔案能夠認識我們定義的屬性, 不至于我們在寫這些自定義的屬性報錯是, 需要加入如下schemas: http://schemas.android.com/apk/res/[your package name] 或 http://schemas.android.com/apk/res-auto (推薦使用) 例子如下:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.zuimeia.imagewidthnumview.ImageWithNumView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textColor="@color/blue"
app:textSize="13sp"/>
</RelativeLayout>
舊的官方文檔建議使用使用第一種, 但現在建議使用第二種 (Android Studio 強烈建議使用第二種)自動去尋找哪些屬性, 就是 代碼提示好像有點問題
3. 讀取attr 我們在xml 定義了 屬性, 需要在View 中讀取出這些屬性 例子如下:
public ImageWithNumView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
LogUtil.d(TAG, "textColor = " + textColor);
LogUtil.d(TAG, "textSize = " + textSize);
}
通過上面的方式 就可以讀取我定義的attr屬性了 AttributeSet 相關文檔, 裡面還有一些其他相關的方法 http://developer.android.com/reference/android/util/AttributeSet.html
通過AttributeSet 擷取定義的寬高:
for (int i = 0; i < attrs.getAttributeCount(); i++) {
if ("layout_height".equals(attrs.getAttributeName(i))) {
String h = attrs.getAttributeValue(i);
LogUtil.d(TAG, "h = " + h);
} else if ("layout_width".equals(attrs.getAttributeName(i))) {
String w = attrs.getAttributeValue(i);
LogUtil.d(TAG, "w = " + w);
}
}
打出來的log 是這樣的:
ImageWithNumView: w = 10.0dip
ImageWithNumView: h = 20.0dip