Android群英传读书笔记——第三章:Android控件架构和自定义控件详解

第三章目录

3.1 Android控件架构
3.2 View的测量
3.3 View的绘制
3.4 ViewGroup的测量
3.5 ViewGroup的绘制

  • 3.6 自定义View 
  • 3.6.1 对现有的空间进行拓展
  • 3.6.2 创建复合控件
  • 3.6.3 重写View来实现全新的空间

3.7 自定义ViewGroup
3.8 事件拦截机制分析

第三章读书笔记

3.1 Android控件架构

控件大致分为两类:

  • View:视图控件,子控件
  • ViewGroup:父控件,可以包含多个View
  • 两者之间的关系:整个界面是一个树形结构,上层控件负责下层子控件的测量与绘制,并传递交互事件

UI界面架构:

  • Activity都包含一个Window对象,通常由PhoneWindow来实现
  • PhoneWindow将一个DecorVIew作为根View,Decor译为“装饰”,可见是什么意思了
  • DecorView是整个Window界面的对顶层的View
  • DecorView中只有一个子元素为LinearLayout,包含状态栏、标题栏、内容栏
  • 我们常见的Activity的setContentView()就是设置内容布局,看看图吧,就能明白很多啦

                                           

3.2 View的测量

View的测量在onMeasure()方法中进行

MeasureSpec类,译为“测量规范”,可见是什么意思了,32为int值,高2位为测量的模式,低30位为测量的大小

测量的模式:

  • EXACTLY:译为“精确的”,指定宽和高为准确的数值,或者match_parent时
  • AT_MOST:译为“最多的”,指定宽和高为wrap_content时
  • UNSPECIFIED:未指定模式,想要多大就多大,一般自定义控件的时候使用

View类默认的onMeasure()方法只支持EXACTLY,想要其他的模式得重写onMeasure()方法

讲一个简单的实例,首先重写onMeasure()方法:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

点进super.onMeasure方法中,我们发现最终会调用setMeasuredDimension(int measuredWidth, int mewsuredHeight)方法将测量的结果设置进去,很明显译为“设置测量尺寸”,我们调用自定义的方法分别对宽高进行重新定义:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
}

下面以measureWidth()方法为例:

private int measureWidth(int measureSpec) {
 // 初始默认一个值
   int result = 0;
// 测量的模式,那三种模式
   int specMode = MeasureSpec.getMode(measureSpec);
// 测量的尺寸
   int specSize = MeasureSpec.getSize(measureSpec);
// 如果是精确模式,就直接赋值
   if (specMode == MeasureSpec.EXACTLY) {
       result = specSize;
// 如果是其他两种模式,指定长度  
 } else {
       result = 200;
// 如果是最大值模式,取指定的200与specSize的最小值
       if (specMode == MeasureSpec.AT_MOST) {
           result = Math.min(result, specSize);
       }
   }
   return result;
}

可以发现,当指定warp_content属性时,View就获得一个默认值200px,而不是去填充整个父布局了

3.3 View的绘制

测量好一个View后,我们通过重写View类中的onDraw()方法来绘图,必须在Canvas上画图,译为“画布”

如果在onDraw()方法中,就直接只用它传的参数Canvas进行绘图,如果在其他地方就得自己创建一个Canvas对象

Canvas canvas = new Canvas(Bitmap);

这个过程是装载画布,这个bitmap会存储所有绘制在Canvas的像素信息,然后我们就可以调用canvas的各种drawXXX方法,画各种各样的图形了

3.4 ViewGroup的测量

通过遍历所有子View,调用子View的onMeasure()方法来获得每一个子View的结果

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
    }
 }

View测量完毕后,通常去重写onLayout()方法来控制其子View显示位置的逻辑

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    for (int i = 0; i < getChildCount(); i++) {
        this.getChildAt(i).layout(l, t, r, b);
    }
}

3.5 ViewGroup的绘制

ViewGroup通常不需要绘制,如果不是指定ViewGroup的背景颜色,那么ViewGroup的onDraw()方法都不会被调用,但是,

ViewGroup会使用dispatchDraw()方法来绘制子View

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
}

3.6 自定义View

在View中通常有以下一些比较重要的回调方法:

  • onFinishInflate():从XML加载组件后回调
  • onSizeChanged():组件大小改变是回调
  • onMeasure():回调该方法进行测量
  • onLayout():回调该方法来确定显示的位置
  • onTouchEvent():监听到触摸事件时回调

通常情况下,有三种方法实现自定义控件:

  • 对现有控件进行扩展
  • 通过组合来实现新的控件
  • 重写View来实现全新的控件

3.6.1 对现有控件进行扩展

1、自定义TextView绘制两层背景

public class MyTextView extends TextView {

    private Paint paint1, paint2;

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    /**
     *  初始化画笔,设置画笔1为蓝色,画笔2为黄色,style都是实心的线
     */
    private void initPaint() {
        paint1 = new Paint();
        paint1.setColor(getResources().getColor(android.R.color.holo_blue_light));
        paint1.setStyle(Paint.Style.FILL);
        paint2 = new Paint();
        paint2.setColor(Color.YELLOW);
        paint2.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 绘制外层矩形
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint1);
        // 绘制内层矩形
        canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, paint2);
        // 需要保存
        canvas.save();
        // 绘制文字前平移10像素
        canvas.translate(10, 0);
        // 父类完成的方法,即绘制文本
        super.onDraw(canvas);
        canvas.restore();
    }
}

2、文字闪动效果

public class FlashTextView extends TextView {

    int mViewWidth = 0;
    private Paint mPaint;
    // 线性渐变
    private LinearGradient mLinearGradient;
    // Matrix 变形矩阵,对图像做4种基本转换,平移、旋转、缩放、错切,作用对象是bitmap
    private Matrix matrix;
    private int mTranslate;

    public FlashTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mViewWidth == 0) {
            mViewWidth = getMeasuredWidth();
            if (mViewWidth > 0) {
                mPaint = getPaint();
            // 两个构造方法,这是其中之一,
            // 1-4、起始和结束渲染xy坐标
            // 5、颜色数组
            // 6、位置数组(也可以为null)
            // 7、平铺方式
                mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0, new int[]{Color.BLUE, 0xffffffff, Color.BLUE},
                        null, Shader.TileMode.CLAMP);
            // 设置渲染器
                mPaint.setShader(mLinearGradient);
                matrix = new Matrix();
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (matrix != null) {
            mTranslate += mViewWidth + 5;
            if (mTranslate > 2 * mViewWidth / 5) {
                mTranslate = -mViewWidth;
            }
        // 平移的方法
            matrix.setTranslate(mTranslate, 0);
            mLinearGradient.setLocalMatrix(matrix);
        // 延迟刷新界面的方法,在子线程中执行
            postInvalidateDelayed(100);
        }
    }
}

3.6.2 创建复合控件

3.6.2.1 定义属性

在values文件夹中创建一个attrs.xml文件来自定义属性

  • reference:参考某一资源id,比如图片id
  • color:颜色
  • boolean:布尔值
  • dimension:尺寸值
  • float:浮点值
  • integer:整型值
  • string:字符串
  • fraction:百分数
  • enum:枚举值,比如说LinearLayout的orientation属性有两个值,horizontal和vertical
  • flag:位或运算,比如某一个mode,可以有或运算,好多种

属性定义可以定义多种类型值

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TopBar">
        <attr name="title" format="string" />
        <attr name="titleTextSize" format="dimension" />
        <attr name="titleTextColor" format="color" />
        <attr name="leftTextColor" format="color" />
        <attr name="leftBackground" format="reference|color" />
        <attr name="leftText" format="string" />
        <attr name="rightTextColor" format="color" />
        <attr name="rightBackground" format="reference|color" />
        <attr name="rightText" format="string" />
    </declare-styleable>
</resources>

通过TypeArray得到所有的属性,并且通过各种get方法得到对应的属性值

        //通过这个方法,将你在attrs.xml文件中定义的declare-styleable
        //的所有属性的值存储到TypedArray中
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        //从TypedArray中取出对应的值来设置的属性赋值
        mLeftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
        mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
        mLeftText = ta.getString(R.styleable.TopBar_leftText);

        mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
        mRightBackgroup = ta.getDrawable(R.styleable.TopBar_rightBackground);
        mRightText = ta.getString(R.styleable.TopBar_rightText);

        mTitleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize, 10);
        mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);
        mTitle = ta.getString(R.styleable.TopBar_title);

        //获取完TypedArray的值之后,一般要调用recycle方法来避免重复创建时候的错误
        ta.recycle();

3.6.2.2 组合控件

就是将得到的属性值给控件设置一下,其实这里还不如用一个View来LayoutInflater一个布局,这样就不用newButton了,后面的点击事件接口就不写了,其实感觉写个接口比较有点繁琐了,在TopBar中再定义几个方法,get左边或者右边的Text或者Drawable,直接setOnClickListener就好了,比如标题常设置,我们就可以再定义一个setTitle方法,其实可以思考一下我的项目中志远大神写的Topbar,感觉比这个好多了

        mLeftButton = new Button(context);
        mRightButton = new Button(context);
        mTitleView = new TextView(context);

        //为创建的元素赋值
        mLeftButton.setTextColor(mLeftTextColor);
        mLeftButton.setBackground(mLeftBackground);
        mLeftButton.setText(mLeftText);

        mRightButton.setTextColor(mRightTextColor);
        mRightButton.setBackground(mRightBackgroup);
        mRightButton.setText(mRightText);

        mTitleView.setText(mTitle);
        mTitleView.setTextColor(mTitleTextColor);
        mTitleView.setTextSize(mTitleTextSize);
        mTitleView.setGravity(Gravity.CENTER);

        //为组件元素设置相应的布局元素
        mLeftParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mLeftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        addView(mLeftButton, mLeftParams);
        mRightParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        addView(mRightButton, mRightParams);
        mTitleParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mTitleParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        addView(mTitleView, mTitleParams);

3.6.2.3 引用UI模板

1、在布局文件中,看到如下一行代码,我们才可以用android来引用Android的系统属性:

xmlns:android="http://schemas.android.com/apk/res/android"

2、那么在使用我们自定义的控件时候,也就是第三方的控件,都要做如下的声明,记得之前app都是红字报错,还不知道咋回事,简直萌萌哒哈哈

xmlns:app="http://schemas.android.com/apk/res-auto"

3.6.3 重写View来实现全新的控件

3.6.3.2 弧线展示图

public class CircleProgressView extends View {
    // 定义长度,圆的直径,圆角值
    private int mCircleXY;
    private int length;
    private float mRadius;
    // 三根笔,自己定义风格
    private Paint mCirclePaint;
    private Paint mArcPaint;
    private Paint mTextPaint;
    private String mShowText = "Hensen_";

    private int mTextSize = 25;
    private float mSweepValue = 270;

    public CircleProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取屏幕高宽
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        length = wm.getDefaultDisplay().getWidth();
        init();
    }
    // 设置比例值的方法
    private void init() {
        mCircleXY = length / 2;
        mRadius = (float) (length * 0.5 / 2);

        mCirclePaint = new Paint();
        mCirclePaint.setColor(Color.BLUE);

        mArcPaint = new Paint();
        mArcPaint.setStrokeWidth(50);
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setColor(Color.BLUE);

        mTextPaint = new Paint();
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextSize(mTextSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //矩形
        RectF mArcRectF = new RectF((float) (length * 0.1), (float) (length * 0.1), (float) (length * 0.9), (float) (length * 0.9));
        //绘制圆
        canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint);
        //绘制弧线
        canvas.drawArc(mArcRectF, 270, mSweepValue, false, mArcPaint);
        //绘制文字
        canvas.drawText(mShowText, 0, mShowText.length(), mCircleXY, mCircleXY + (mTextSize / 4), mTextPaint);
    }

    public void setSweepValue(float sweepValue) {
        if (sweepValue != 0) {
            mSweepValue = sweepValue;
        } else {
            mSweepValue = 25;
        }
        invalidate();
    }
}

当用户不指定具体的比例值时,可以调用以下代码来设置相应的比例值

CircleProgressView circleProgressView = (CircleProgressView) findViewById(R.id.circle);
circleProgressView.setSweepValue(270);

3.6.3.2 音频条形图

public class MusicView extends View {
    // 定义宽度,矩形高度,矩形数量,渐变器,画笔
    private int mWidth;
    private int mRectHeight;
    private int mRectWidth;
    private int mRectCount = 20;
    private LinearGradient mLinearGradient;
    private Paint mPaint=new Paint();
    // 当前高度,用来变化条形图
    private float currentHeight;
    private int offset = 5;
    private double mRandom;

    public MusicView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    // 设置渐变器
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
        mRectHeight = getHeight();
        mRectWidth = (int) (mWidth * 0.6 / mRectCount);
        mLinearGradient = new LinearGradient(0, 0, mRectWidth, mRectHeight, Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP);
        mPaint.setShader(mLinearGradient);
    }
    // 开始画图并设置延时
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //遍历绘制矩形,留中间间隔
        for (int i = 0; i < mRectCount; i++) {
            //开始绘制
            canvas.drawRect((float) (mWidth * 0.4 / 2 + mRectWidth * i + offset),
                    currentHeight, (float) (mWidth * 0.4 / 2 + mRectWidth * (i + 1)), mRectHeight, mPaint);
        }
        //获取随机数
        mRandom = Math.random();
        currentHeight = ((float) (mRectHeight * mRandom));
        //延迟300去刷新
        postInvalidateDelayed(300);
    }

}

3.7 自定义ViewGroup

通常重写如下几个方法:

onMeasure()方法:对子控件进行测量

onLayout()方法:子View的位置

onTouchEvent()方法:增加响应事件

public class CustomScrollView extends ViewGroup {
    // 屏幕的高度、Scroller、
    private int mScreenHeight;
    private Scroller mScroller;
    private int mLastY;
    private int mStart;
    private int mEnd;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取屏幕高宽
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        mScreenHeight = wm.getDefaultDisplay().getHeight();
        mScroller = new Scroller(getContext());
    }
    // 放置子控件的位置,通过for循环,判断子控件是否是可见状态,
    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        int childCount = getChildCount();
        MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams();
        mlp.height = mScreenHeight * childCount;
        setLayoutParams(mlp);

        for (int j = 0; j < childCount; j++) {
            View child = getChildAt(j);
            if (child.getVisibility() != View.GONE) {
                child.layout(i, j * mScreenHeight, i2, (j + 1) * mScreenHeight);
            }
        }
    }
    // 对子控件进行测量
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; ++i) {
            View childView = getChildAt(i);
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 得到触摸的y坐标
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = y;
                // 相对于左上角的Y轴偏移量
                mStart = getScrollY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                // 滑动的距离
                int dy = mLastY - y;
                // 滑动为负值置为0
                if (getScrollY() < 0) {
                    dy = 0;
                }
                if (getScrollY() > getHeight() - mScreenHeight) {
                    dy = 0;
                }
                // 滑动
                scrollBy(0, dy);
                // 最终滑动到哪里
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:
                // 最终抬起的位置
                mEnd = getScrollY();
                // y轴滑动了多少距离
                int dScrollY = mEnd - mStart;
                // 如果大于0,往下滑
                if (dScrollY > 0) {
                    // 如果滑动距离小于三分之一,直接滑到原位置
                    if (dScrollY < mScreenHeight / 3) {
                        mScroller.startScroll(0, getScrollY(), 0, -dScrollY);
                    // 否则直接滑一屏
                    } else {
                        mScroller.startScroll(0, getScrollY(), 0, mScreenHeight - dScrollY);
                    }
                // 如果<0,往上滑
                } else {
                    // 滑动距离小于三分之一,直接滑到原位置
                    if (-dScrollY < mScreenHeight / 3) {
                        mScroller.startScroll(0, getScrollY(), 0, -dScrollY);
                    // 否则直接滑一屏
                    } else {
                        mScroller.startScroll(0, getScrollY(), 0, -mScreenHeight - dScrollY);
                    }
                }
                break;
        }
        postInvalidate();
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            scrollTo(0, mScroller.getCurrY());
            postInvalidate();
        }
    }
}

3.8 事件拦截机制分析

事件拦截机制三个重要方法

  • dispatchTouchEvent():分发事件,dispatch译为 “调度,派遣,分发” 的意思
  • onInterceptTouchEvent():拦截事件,Intercept译为 “拦截,截击”的意思
  • onTouchEvent():处理事件

举一个例子说明事件分发机制:

  • ViewGroupA:处于视图最下层
  • ViewGroupB:处于视图中间层
  • View:处于视图最上层

1、正常的事件分发机制流程:总经理—>部长—>我

  • ViewGroupA dispatchTouchEvent
  • ViewGroupA onInterceptTouchEvent
  • ViewGroupB dispatchTouchEvent
  • ViewGroupB onInterceptTouchEvent
  • View dispatchTouchEvent
  • View onTouchEvent
  • ViewGroupB onTouchEvent
  • ViewGroupA onTouchEvent

2、若ViewGroupB的onInterceptTouchEvent()方法返回true的分发机制流程:总经理—>部长

  • ViewGroupA dispatchTouchEvent
  • ViewGroupA onInterceptTouchEvent
  • ViewGroupB dispatchTouchEvent
  • ViewGroupB onInterceptTouchEvent
  • ViewGroupB onTouchEvent
  • ViewGroupA onTouchEvent

3、若View的onTouchEvent()方法返回true的分发机制流程:总经理—>部长—>我,我不向上报告,在我这处理

  • ViewGroupA dispatchTouchEvent
  • ViewGroupA onInterceptTouchEvent
  • ViewGroupB dispatchTouchEvent
  • ViewGroupB onInterceptTouchEvent
  • View dispatchTouchEvent
  • View onTouchEvent

4、若ViewGroupB的onTouchEvent()方法返回true的分发机制流程:总经理—>部长—>我,部长不向上报告,在他那处理

  • ViewGroupA dispatchTouchEvent
  • ViewGroupA onInterceptTouchEvent
  • ViewGroupB dispatchTouchEvent
  • ViewGroupB onInterceptTouchEvent
  • View dispatchTouchEvent
  • View onTouchEvent
  • ViewGroupB onTouchEvent

5、简单的说dispatchTouchEvent()和onInterceptTouchEvent()是从下往上一层一层分发下去的,而onTouchEvent()是从上往下一层一层分发下去的

dispatchTouchEvent(),我们在这里先不考虑它

onInterceptTouchEvent(),

  • true:拦截,到我这就停止了,不往下分发了
  • false:不拦截,正常分发

onTouchEvent(),

  • true:处理,到我这就处理了,不往上提交去审核了
  • false:不处理,正常交给上级

总结

1、在这章主要还是接触到了控件的一些知识,View测量,绘制,Canvas和Paint等

2、自定义控件

  • 对现有控件进行扩展,比如继承TextView
  • 采用组合控件,比如自定义一个TopBar
  • 完全重写View来实现,如写个环形图,自定义ScrollView

3、对事件分发机制有一些了解

哈~好久没发博客了,这大半个月一直都在忙,写了一些项目内部的总结文章,以后还是要抽出事件多多写博客呀,坚持加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值