Android已经提供了一系列基础控件和xml属性来帮助你创建自定义控件。
1.View的子类
View在Android是最基础的几个控件之一, 所有的控件均继承自View,你也可以直接继承View也可以继承其他的控件比如ImageView等。至少需要提供一个构造函数,其中Context和AttributeSet作为参数。 举例如下:
class PieChart extends View{
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
2. 自定义属性
1) 添加自定义属性<declare-styleable>
到xml文件中
2) 在xml的<declare-styleable>
中,指定属性的值
3) 在view中获取xml中的值
4) 将获取的值应用到view中
举例说明:
添加 到你的程序中,习惯上一般是放在res/values/attrs.xml文件中,例如:
<resources>
<declare-styleable name="PieChart">
<attr name="showText" format="boolean" />
<attr name="labelPosition" format="enum">
<enum name="left" value="0"/>
<enum name="right" value="1"/>
</attr>
</declare-styleable>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
<com.example.customviews.charting.PieChart
custom:showText="true"
custom:labelPosition="left" />
</LinearLayout>
标准的组件的命名空间一般是http://schemas.android.com/apk/res/android,
自定义的命名空间是http://schemas.android.com/apk/res/[yourPackageName],
注意:
xmlns:custom中的custom可以使用任意的字符,但要和下面的控件的定义中的字符要保持一致。
xml中的tag:com.example.customviews.charting.PieChart,需要的完整的包名
3.应用自定义的属性值
当View被创建的时候,可以通过AttributeSet读取所有的定义在xml中的属性,在构造函数中通过obtainStyledAttributes读取attrs,
该方法会返回一个TypeArray数组。通过TypeArray可以读取到已经定义在XML中的方法。下面的例子展示了读取上文中的xml属性值。
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.PieChart,
0, 0);
try {
mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
} finally {
a.recycle();
}
}
需要强调的是, TypeArray使用完毕后必须要recycle,不然会发生内存泄露。
4.添加自定义的方法和事件
自定义属性只能在view初始化的时候被应用到控件中。 所以可以为每一个属性添加getter和setter,来方便操作
public boolean isShowText() {
return mShowText;
}
public void setShowText(boolean showText) {
mShowText = showText;
invalidate();
requestLayout();
}