GraphableButton类实现Android UI开发
2010-08-20 01:58:00 来源:WEB开发网从Android 1.6开始,系统设置中的电池使用记录提供了一种简单的自绘Button按钮演示-GraphableButton类,通过 GraphableButton我们可以很清晰的了解到前几次Android123讲到的UI开发要点。
public class GraphableButton extends Button { //从Button类继承
private static final String TAG = "GraphableButton";
static Paint[] sPaint = new Paint[2]; //定义两种颜色
static {
sPaint[0] = new Paint();
sPaint[0].setStyle(Paint.Style.FILL);
sPaint[0].setColor(0xFF0080FF);
sPaint[1] = new Paint();
sPaint[1].setStyle(Paint.Style.FILL);
sPaint[1].setColor(0xFFFF6060);
}
double[] mValues;
public GraphableButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setValues(double[] values, double maxValue) { //设置显示范围,下文提到
mValues = values.clone();
for (int i = 0; i < values.length; i++) {
mValues[i] /= maxValue;
}
}
@Override
public void onDraw(Canvas canvas) { //重写onDraw直接绘制
Log.i(TAG, "onDraw: w = " + getWidth() + ", h = " + getHeight());
int xmin = getPaddingLeft();
int xmax = getWidth() - getPaddingRight();
int ymin = getPaddingTop();
int ymax = getHeight() - getPaddingBottom();
int startx = xmin;
for (int i = 0; i < mValues.length; i++) {
int endx = xmin + (int) (mValues[i] * (xmax - xmin));
canvas.drawRect(startx, ymin, endx, ymax, sPaint[i]); //通过canvas绘制范围
// 该方法原型 drawRect(float left, float top, float right, float bottom, Paint paint)
startx = endx;
}
super.onDraw(canvas);
}
}
调用方法很简单,和普通的Button没有什么区别,这里我们仅仅多定义了setValues方法,Android开发网提醒网哟注意布局文件
Tags:GraphableButton 实现 Android
编辑录入:coldstar [复制链接] [打 印]更多精彩
赞助商链接