android复习路之自定义View篇

来源:互联网 发布:仙剑奇侠传6mac版 编辑:程序博客网 时间:2024/05/18 12:02

自定义view需要重写两个函数:onMeasure() 和 onDraw()。

onMeasure()用来测量view的大小。

测量中的三种模式

EXACTLY 当我们为view 精确的指定它的大小的时候,还有指定为match_parent时会使用该模式

AT_MOST 当view属性wrap_content的时候会使用这个模式

UNSPECIFIED 这种模式我暂时不知道什么时候会被调用自己各种调用方式都试过都没调用过,等以后遇到了补充进来

自定义view 默认支持EXACTLY 如果想让它支持wrap_content属性就要重写onMeasure()。

自定义view 一定要有两个构造函数:public Myview (Context context)()和public Myview ( Context context,AttributrSet attrs)

onDraw()就是用来进行绘制我们需要的效果的,用Canva 进行绘制。

样例代码:

public class MyView extends View {    private int defaultSize;    public MyView(Context context) {        super(context);    }    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);    }    private int getMySize(int defaultSize, int measureSpec) {        int mySize = defaultSize;        int mode = MeasureSpec.getMode(measureSpec);        int size = MeasureSpec.getSize(measureSpec);        switch (mode) {            case MeasureSpec.UNSPECIFIED: {                mySize = defaultSize;                break;            }            case MeasureSpec.AT_MOST: {//如果测量模式是最大取值为size                //我们将大小取最大值,你也可以取其他值                mySize = size;                break;            }            case MeasureSpec.EXACTLY: {//如果是固定的大小,那就不要去改变它                mySize = size;                break;            }        }        return mySize;    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        int width = getMySize(defaultSize, widthMeasureSpec);//分别调用getsize()进行测量计算        int height = getMySize(defaultSize, heightMeasureSpec);        setMeasuredDimension(width, height);//一定记得添加值    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        int r=getMeasuredHeight()/2;        int conterX=getLeft()+r;        int conterY=getTop()+r;        Paint paint=new Paint();        paint.setColor(Color.GRAY);        canvas.drawCircle(conterX,conterY,r,paint);    }}
注:这段代码是继承于view 不需要单独创建xml,布局写在mainactivity的布局文件中就可以

布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.zobject.myview.MainActivity">        <com.example.zobject.myview.MyView            android:layout_width="wrap_content"            android:layout_height="100px"            android:background="#ff0000"            /></LinearLayout>
注:自定义view一定要写完整的包名。

效果图


自定义view group 在后续复习中补充,还有canvas在后续中要写一篇。 

0 0
原创粉丝点击