1. 继承自android.view.View.
2. 自定义属性
3. 重写onMeasure() 和 onDraw()
1. 继承自View
class PieChart extends View {
public PieChart(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
}
2. 自定义属性
- 在<declare-styleable>中声明属性
- 在xml layout文件中设置这些属性
- 程序运行的时候取得这些属性
- 设置这些属性到我们自定义的view中去
在<declare-styleable>中声明属性:
<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>
custom:namespace的名字
http://schemas.android.com/apk/res/com.example.customviews
= http://schemas.android.com/apk/res/[your package name]
public PieChart(Context ctx, AttributeSet attrs) {
super(ctx, 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();
}
}
设置这些属性到我们自定义的view中去
上面得到自定义的属性之后,就可以在我们的程序中去使用它们了,比如
public boolean isShowText() {
return mShowText;
}
public void setShowText(boolean showText) {
mShowText = showText;
invalidate();
requestLayout();
}
3. 重写onMeasure() 和 onDraw()
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec),resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}