Android App中,所有的用户界面元素都是由View和ViewGroup的对象构成的,View是绘制在屏幕上的用户能与之交互的一个对象。很多时候android原生的控件不能满足我们的需求,这时我们往往需要自定义控件。自定义控件做法:继承View或继承View的子类(TextView、ImageView......)。
简单的自定义View实现:
一、编写一个类继承View
二、在布局中使用自定义的类
/**
* 自定义简单的View:画一个矩形形按键
* @author rongyun
*/
public class CustomView extends View{
private Paint paint;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
//画笔
paint = new Paint();
paint.setColor(Color.GREEN);
//画矩形
RectF rectF=new RectF();
rectF.set(10, 10, 300, 200);
canvas.drawRect(rectF, paint);
}
}
自定义View高级应用
一、编写自己的attrs.xml文件,定义自己的属性
二、继承View,实现attrs.xml定义的属性
三、布局文件中使用自定义的控件
public class CustomView extends View {
private Integer downcolor;
private Integer upcolor;
private Paint paint;
private Integer color;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.PieChart, 0, 0);
try {
//设置默认颜色
downcolor = typedArray.getColor(R.styleable.PieChart_downcolor,
Color.BLUE);
upcolor = typedArray.getColor(R.styleable.PieChart_upcolor,
Color.GREEN);
} catch (Exception e) {
Log.e("log", "error");
} finally {
typedArray.recycle();
}
paint = new Paint();
color = upcolor;
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(color);
canvas.drawCircle(getWidth() / 2, (getHeight() / 2),
((getHeight() / 2) - 1), paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int i = event.getAction();
switch (i) {
case MotionEvent.ACTION_DOWN:
color = downcolor;
break;
case MotionEvent.ACTION_UP:
color = upcolor;
break;
}
invalidate();
return super.onTouchEvent(event);
}
}