自定义View

分类:
  • 继承View重写onDraw方法:这种情况下,需要自己支持wrap_content,并且padding也需要自己处理。
  • 继承ViewGroup派生特殊的layout:需要处理ViewGroup的测量和布局这两个过程,并同时处理子元素的测量和布局过程。
  • 继承特定的View(比如TextView):这种方法一般不需要自己处理wrap_content和padding。
  • 继承特定的ViewGroup(比如LinearLayout)
自定义View须知:
  • 对于继承View和ViewGroup的情况下,需要处理wrap_content和padding
  • 尽量不要在View中使用handler,因为View内部本身就提供了post系列。
  • View中如果有线程或动画,需要及时停止。当View不可见或View的Activity推出时,要及时停止线程和动画,否则有可能造成内存泄漏。我们一般是在onDetacheddFromWindow中去停止,因为当View不可见或Activity退出时,该方法会被调用。
  • View带有滑动嵌套情形时,需要处理好滑动冲突。
示例一:继承View重写onDraw方法

这里我们来实现自定义圆,首先看到onMeasure方法:
解析传入的宽高 --- 考虑wrap_contet情况 --- 若存在,则设置一个默认的值

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取到width,height对应的mode和size
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        //考虑wrap_content的情况,需要为其设置默认的值,这里设置为200dp
        //对于宽高都设定为wrap_content时
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200, 200);
        }
        //对于高设定为wrap_content的情况
        else if (widthSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200, heightSpecSize);
        }
        //对于宽设定为wrap_content的情况
        else if (heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize, 200);
        }
    }

接下来是,实现onDraw方法:
要注意的一点是,这里要处理padding的情况

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取到padding值
        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        //获取到真实的宽高
        int height = getHeight() - paddingTop - paddingBottom;
        int width = getWidth() - paddingLeft - paddingRight;
        //以最小的值/2作为半径
        int radius = Math.min(width, height) / 2;
        //进行画圆
        canvas.drawCircle(paddingLeft + width/2 , paddingTop + height/2, radius, mPaint);
    }

我们还可以为其设置自定义属性:
a. 在res/values中创建一个xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleView">
        <attr name="circle_color" format="color"/>
    </declare-styleable>
</resources>

其中,name表示为属性名,format表示为属性类型,这里是color类型。

b. 在布局中引入:xmlns:app = "http://schemas.android.com/apk/res-auto"
并设置自定义控件:

<com.example.viewtest.CircleView
        android:id="@+id/circleView"
        android:background="#000"
        app:circle_color = "@color/gray_color"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content" />

我们可以看到其中的app:cirle_color表示为自定义的属性。

c. 在自定义View中获取到属性:

//获取到自定义属性
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
//获取到自定义属性的值,其中第二个参数为默认参数,表示若不存在,则设置为默认值
mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);

完整代码如下:

public class CircleView extends View {
    //定义颜色和画笔
    private int mColor = Color.RED;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CircleView(Context context) {
        super(context);
        init();
    }

    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取到自定义属性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        //获取到自定义属性的值,其中第二个参数为默认参数,表示若不存在,则设置为默认值
        mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
        init();
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
        init();
    }

    //给画笔设置颜色
    private void init(){
        mPaint.setColor(mColor);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取到width,height对应的mode和size
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        //考虑wrap_content的情况,需要为其设置默认的值,这里设置为200dp
        //对于宽高都设定为wrap_content时
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200, 200);
        }
        //对于高设定为wrap_content的情况
        else if (widthSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200, heightSpecSize);
        }
        //对于宽设定为wrap_content的情况
        else if (heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize, 200);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取到padding值
        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        //获取到真实的宽高
        int height = getHeight() - paddingTop - paddingBottom;
        int width = getWidth() - paddingLeft - paddingRight;
        //以最小的值/2作为半径
        int radius = Math.min(width, height) / 2;
        //进行画圆
        canvas.drawCircle(paddingLeft + width/2 , paddingTop + height/2, radius, mPaint);
    }
}

实现效果:


自定义View.png
实例二:自定义的ViewGroup

实现一个类似ViewPager的自定义ViewGroup:

a. 实现onMeasure方法:
遍历孩子元素进行测量 --- 考虑wrap_content情况:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //定义两个变量,作为测量的宽和高
        int measureWidth = 0;
        int measureHeight = 0;
        //获取到孩子个数
        final int childCount = getChildCount();
        //遍历孩子元素,对孩子元素分别进行测量
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        
        //解析宽高,获取到模式和大小
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        //考虑wrap_content情况
        
        //孩子为0的情况下
        if (childCount == 0){
            setMeasuredDimension(0 ,0);
        }
        //宽高都是为wrap_content
        else if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            final View childView = getChildAt(0);
            //获取到对应的宽度
            measureWidth = childView.getMeasuredWidth() * childCount;
            //设置孩子的高度作为当前高度
            measureHeight = childView.getMeasuredHeight();
            setMeasuredDimension(measureWidth, measureHeight);
        } else if(widthSpecMode == MeasureSpec.AT_MOST){
            final  View childView = getChildAt(0);
            measureWidth = childView.getMeasuredWidth() * childCount;
            setMeasuredDimension(measureWidth, heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST){
            final View childView = getChildAt(0);
            measureHeight = childView.getMeasuredHeight();
            setMeasuredDimension(widthSpecSize, measureHeight);
        }
    }

b. 实现布局方式:
遍历所有的孩子元素,若孩子元素不为GONE模式,则进行放置其位置。

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childLeft = 0;
        final int childCount = getChildCount();
        mChildrenSize = childCount;
        //遍历所有的孩子元素
        for (int i = 0; i < childCount; i ++){
            final View childView = getChildAt(i);
            //若当前的孩子元素不为GONE,则对该孩子进行放置其位置
            if (childView.getVisibility() != View.GONE){
                final int childWidth = childView.getMeasuredWidth();
                mChildWidth = childWidth;
                childView.layout(childLeft, 0, childLeft + childWidth, childView.getMeasuredHeight());
                childLeft += childWidth;
            }
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,719评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,337评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,887评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,488评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,313评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,284评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,672评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,346评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,644评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,700评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,457评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,316评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,706评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,261评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,648评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,859评论 2 335

推荐阅读更多精彩内容