自定义控件的四种模式

来源:互联网 发布:手机淘宝1元秒杀入口 编辑:程序博客网 时间:2024/05/14 13:48

一.伪自定义控件

1.静态方法,通过在布局中用<include>直接将写好的控件布局添加到指定位置


2.动态绑定,通过代码调用addView方法进行添加

二.二、继承View,处理自身事件响应的自定义控件
View.ontouchEvent返回值为true截获事件,并处理

类似于画图板的view

public class DrawView extends View {
Paint paint;
Path path;
float currentX, currentY;
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();//初始化画笔
paint.setColor(Color.RED);
paint.setStrokeWidth(12);
paint.setStyle(Paint.Style.STROKE);
path = new Path();
}


public DrawView(Context context) {
super(context);

}


@Override
protected void onDraw(Canvas canvas) {
if (path != null) {
canvas.drawPath(path, paint);
}
super.onDraw(canvas);
}


@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
currentX = event.getX();
currentY = event.getY();
path.moveTo(currentX, currentY);//移动到起始点
break;
case MotionEvent.ACTION_MOVE:
currentX = event.getX();
currentY = event.getY();
path.lineTo(currentX, currentY);//划线
invalidate();//重绘
break;


}
return true;
}
}

三.在第二层基础上,设置系统认可属性的自定义控件,设置自身标志位

创建自己的textView控件

public class MyTextView extends View {    private Paint paint;    protected String text;    protected int textcolor;    protected float textsize;    public MyTextView(Context context) {        super(context);    }    public MyTextView(Context context, AttributeSet attrs) {        super(context, attrs);        //把继承类的属性和自己定义的属性揉起来,生成新的控件的全部属性        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);        //关联属性 并初始化        text = array.getString(R.styleable.MyTextView_text);        textsize = array.getDimension(R.styleable.MyTextView_textsize, 50);        textcolor = array.getInt(R.styleable.MyTextView_textcolor, Color.RED);        if (text == null) {            text = "hello world";        }        //使新属性生效        array.recycle();        //初始化画笔        paint = new Paint();        paint.setTextSize(textsize);        paint.setColor(textcolor);    }    public String getText() {        return text;    }    public void setText(String text) {        this.text = text;    }    public int getTextcolor() {        return textcolor;    }    public void setTextcolor(int textcolor) {        paint.setColor(textcolor);        invalidate();        this.textcolor = textcolor;    }    public float getTextsize() {        return textsize;    }    public void setTextsize(float textsize) {        paint.setTextSize(textsize);        invalidate();        this.textsize = textsize;    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        canvas.drawText(text, 50, 70, paint);    }}
4.第三层级在实用性上较差 需要用户自己重写麻烦的onMeasure方法。所以实用的时候可以将自定义控件继承自线性(或其他)布局来回避掉重写onMeasure方法onMeasureonMeasureonMeasureonMeasureonMeasureonMeasure方法

0 0