自己定义的布局,需要自己自定义view,通常继承View然后重写构造方法以及onDraw等函数。同时,我们也可以自定义属性。步骤如下:
- 在项目文件res/value下面创建一个attr.xml文件,该文件包含若干个attr的集合,例如:
<Resources>
<declare-styleable name="MyView">
<attr name="myTextSize"format="dimension"/>
<attr name="myColor"format="color"/>
</declare-styleable>
</Resources>
其中resource是根标签,可以在里面定义若干个declare-styleable,<declare-styleable name=”myView“> 中name定义了变量名称,下面可以再定义多个属性,针对<attr name=”myTextSize” format=”dimension”/>来说,其属性的名称为”myTextSize“,format指定了该属性类型为dimension,只能表示字体的大小。
Format还可以指定其他的类型,比8如:
Reference 表示引用,参考某一资源的ID。
String 表示字符串
Color 表示颜色值
Dimension 表示尺寸值
Boolean表示布尔值
Integer 表示整型值
Float 表示浮点值
Fraction 表示百分数
Enum 表示枚举值
Flag 表示位运算
2.在使用该自定义view的布局文件中加入如下一行:
xmlns :app=”http://schemas.android.com/apk/res/com...“ 注意(后面的com.什么为activity的包名)
3.在自定义view的代码中引入自定义属性。修改构造函数
Context通过调用obtainStyledAttributes方法来获取一个TypeArray,然后又该TypeArray来对属性进行设置,
obtainStyledAttributes方法有三个,我们常用的是有一个参数的obtainStyledAttributes(int[] attrs),其参数直接styleable中获得。
TypedArray a = context.obtainStyledAttributes(attrs ,R.Styleable.MyView);
调用结束后务必调用recycle()方法。否则这次的设定会影响下次的使用。
注意:属性定义时可以指定多种类型值:
1.属性定义:
<declare-styleable name=”名称”>
<attr name=”background” format=”reference|color”/>
</declare-styleable>
2.属性使用:
<ImageView
android:layout_width = “42dip”
android:layout_height=”42dip”
android:background=”@drawable/图片id|颜色#。。。”/>