Andriod: 在xml布局中使用自定义属性
转载:http://www.cnblogs.com/hibraincol/archive/2011/10/27/2227149.html 今天在看android froyo的launcher2 源码的时候,在launcher.xml中看到有这么一段代码:
注意到其中的两处:
和
可以看出在这个布局文件中,使用了自定义属性。 以前没遇到过,既然这里碰到了,就顺便学习下,下面就写个简单的示例,权当学习笔记,便于以后查阅。 1. 定义一些自定义属性 建立一个属性xml文件: values/attrs.xml,内容如下: resources
>
<!-- the relation between the icon and text. -->
attr
name
"relation"
>
enum
"icon_left"
value
"0"
/>
"icon_right"
"1"
/>
"icon_above"
/>
"icon_below"
"3"
/>
</
attr
>
skip
/>
declare-styleable
"IconText"
>
/>
"icon"
format
"reference"
/>
"text"
"string"
/>
"text_size"
"dimension"
/>
"text_color"
"integer"
/>
"space"
/>
declare-styleable
>
>
|
解释如下:
属性relation有4种可选值:icon_left,icon_right,icon_above,icon_below.
属性icon的可选值为引用: 例如:"@/drawbable/icon".
属性text的可选值为string, 例如: "Hello world",也可是string的引用"@string/hello".
属性text_size的可选值为尺寸大小,例如:20sp、18dip、20px等.
属性text_color的可选值为整数,例如:"0xfffffff", 也可以是color的引用"@color/white".
2. 定义一个能够处理这些属性值的view或者layout类
android.content.Context;
class
IconTextView
extends
LinearLayout {
private
final
static
String TAG =
"IconTextView"
;
ICON_LEFT =
0
;
1
;
2
;
3
;
TextView mTextView;
""
;
mTextSize;
IconTextView(Context context,AttributeSet attrs){
(context,attrs);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.IconText);
"mRelation: "
+mRelation);
+mText);
12
);
+mTextSize);
);
+mSpace);
+mIconId);
new
TextView(context);
ImageView(context);
;
;
;
;
;
(mRelation){
ICON_ABOVE:
;
.setOrientation(orientation);
}
可以看出这个LinearLayout 子类IconTextView中只有两个元素,ImageView 和mTextView,通过从xml配置文件中读取属性值来决定icon和text的内容、相对位置及其它属性。
3. 在layout布局文件中使用这个自定布局及其属性
layout/main.xml:
"http://schemas.android.com/apk/res/com.braincol.viewattrs"
"icon_left"
"@drawable/hi"
"hi,how are you!"
"12sp"
>