Swift51.com
麦子学院 头像
麦子学院  2016-09-22 14:36

Android中通过继承系统的控件自定义view方法详解

回复:0  查看:2512  

android开发中,我们android如何实现通过继承系统的控件自定义view呢?其实方法就是通过对OnDraw()方法进行复写来实现的。下面我们举个栗子来看看吧。


继承TextView


textView的背景加上矩形的效果


代码实现


testView的代码


public class TestView extends TextView {


    public TestView(Context context) {

        super(context);

    }


    @Override

    protected void onDraw(Canvas canvas) {

        Paint paint1 = new Paint();

        paint1.setColor(getResources().getColor(android.R.color.holo_blue_light));

        paint1.setStyle(Paint.Style.FILL);

        Paint paint2 = new Paint();

        paint2.setColor(Color.YELLOW);

        paint2.setStyle(Paint.Style.FILL);

        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint1);

        canvas.drawRect(10,10,getMeasuredWidth()-10,getMeasuredHeight()-10,paint2);

        canvas.save();

        canvas.translate(10,0);

        super.onDraw(canvas);

        canvas.restore();

    }

}


布局的代码


public class TestView extends TextView {


    public TestView(Context context) {

        super(context);

    }


    @Override

    protected void onDraw(Canvas canvas) {

        Paint paint1 = new Paint();

        paint1.setColor(getResources().getColor(android.R.color.holo_blue_light));

        paint1.setStyle(Paint.Style.FILL);

        Paint paint2 = new Paint();

        paint2.setColor(Color.YELLOW);

        paint2.setStyle(Paint.Style.FILL);

        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint1);

        canvas.drawRect(10,10,getMeasuredWidth()-10,getMeasuredHeight()-10,paint2);

        canvas.save();

        canvas.translate(10,0);

        super.onDraw(canvas);

        canvas.restore();

    }

}


以上就是android自定义View-继承的方法,希望对大家有所帮助。


文章来源:csdn