第八单元

一、View绘制流程

1、流程

图片.png
  1. measure:确定View的测量宽高
  2. layout:根据测量的宽高确定View在其父View中的四个顶点的位置
  3. draw:将view绘制到屏幕上

2、三种测量模式

MeasureSpec 表示的是一个 32 位的整数值,它的高 2 位表示测量模式 SpecMode,低 30 位表示某种测量模式下的规格大小 SpecSize。
三种测量模式
EXACTLY:精确测量模式,当该视图的 layout_width 或者 layout_height 指定为具体数值或者 match_parent 时生效,表示父视图已经决定了子视图的精确大小,这种模式下 View 的测量值就是 SpecSize 的值。
AT_MOST:最大值模式,当前视图的 layout_width 或者 layout_height 指定为 wrap_content 时生效,此时子视图的尺寸可以是不超过父视图运行的最大尺寸的任何尺寸。
UNSPECIFIED:不指定测量模式,父视图没有限制子视图的大小,子视图可以是想要的任何尺寸,通常用于系统内部,应用开发中很少使用到。

3、getMeasureWidth()与getWidth()区别

一个View 的大小是由View本身和父View两个共同决定
getMeasureWidth:measure阶段确定,是xml中的原始值
getWidth:layout阶段确定,是最终显示的大小
两个值可能相等,可能不相等

如何在onCreate中获取View的高度?

  1. postDelay延迟获取一下
  2. ViewTreeObserver方式获取
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
    view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    Log.i(TAG, "width: " + view.getWidth());
    Log.i(TAG, "height: " + view.getHeight());
    }
    });

4、View,ViewGroup绘制区别

onMeasure:
View只需要确定自己的大小就可,ViewGroup需要先确定子View的大小
onLayout:
View不需要处理,ViewGroup必须实现onLayout来安排子view的位置
onDraw:
View需要实现自己的onDraw就好,ViewGroup通过dispatchDraw以实现对各个子view的绘制

二、自定义view

1、什么是自定义View

使用系统自带的控件重新组合或者继承View、ViewGroup实现特定的效果

2、为什么需要自定义View

现有view不满足需求

3、方式

  1. 继承于android.view.View或者android.view.ViewGroup
    2.继承于android.view.View或者android.view.ViewGroup的相关子类
    3.组合View

4、步骤

1.继承android.view.View或者android.view.ViewGroup
2.onLayout
3.onMeasure
4.onDraw

5、例子

public class CustomView extends View {
    public CustomView(Context context) {
        super(context);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width;
        int height;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        }
        else {
            width = widthSize/2;
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        }
        else {
            height = heightSize/2;
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(100, 100, 100, paint);

        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(20);
        canvas.drawCircle(300, 300, 100, paint);

        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(40);
        paint.setColor(Color.RED);
        canvas.drawText("我是王贤兵", 200, 200, paint);

        paint.setColor(Color.BLUE);
        canvas.drawRect(10, 10, 100, 100, paint);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        canvas.drawBitmap(bitmap, 100, 100, paint);
    }
}

三、自定义view属性

1、values下新建attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="wxb_text_color" format="color" />
        <attr name="wxb_stroke_width" format="dimension" />
    </declare-styleable>
</resources>

注意format的类型:

(1). reference:参考某一资源ID
(2). color:颜色值
(3). boolean:布尔值
(4). dimension:尺寸值
(5). float:浮点值
(6). integer:整型值
(7). string:字符串
(8). fraction:百分数
(9). enum:枚举值
(10). flag:位或运算

2、获取数据

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView);
            mTextColor = typedArray.getColor(R.styleable.CustomView_wxb_text_color, Color.RED);
            mStrokeWidth = typedArray.getDimension(R.styleable.CustomView_wxb_stroke_width, 20);
            typedArray.recycle();
        }
    }

3、例子

public class CustomView extends View {
    private float mStrokeWidth = 20;
    private int mTextColor = Color.RED;
    public CustomView(Context context) {
        super(context);
        init(null);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }
    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView);
            mTextColor = typedArray.getColor(R.styleable.CustomView_wxb_text_color, Color.RED);
            mStrokeWidth = typedArray.getDimension(R.styleable.CustomView_wxb_stroke_width, 20);
            typedArray.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width;
        int height;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        }
        else {
            width = widthSize/2;
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        }
        else {
            height = heightSize/2;
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(100, 100, 100, paint);

        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(mStrokeWidth);
        canvas.drawCircle(300, 300, 100, paint);


        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(40);
        paint.setColor(mTextColor);
        canvas.drawText("我是王贤兵", 200, 200, paint);

        paint.setColor(Color.BLUE);
        canvas.drawRect(10, 10, 100, 100, paint);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        canvas.drawBitmap(bitmap, 100, 100, paint);
    }
}

四、例子

环形进度条

    public void start() {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 360);
        valueAnimator.setDuration(2000);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int v = (int)animation.getAnimatedValue();
                Log.i("Simon", "onAnimationUpdate v:" + v);

                mCurrentValue = v;
                invalidate();//强制更新-通知系统刷新本view
            }
        });
        valueAnimator.start();
    }

    private Paint mCirclePaint = new Paint();
    private Paint mTextPaint = new Paint();
    private Paint mArcPaint = new Paint();
    private float ringSize = 24;//环的宽度
    private int mCurrentValue = 0;

    @Override
    protected void onDraw(Canvas canvas) {
        int centre = getWidth() / 2;
        int radius = (int) (centre - ringSize/2);
        mCirclePaint.setColor(Color.BLACK);//颜色
        mCirclePaint.setStyle(Paint.Style.STROKE);//描边
        mCirclePaint.setStrokeWidth(ringSize);//环的宽度
        mCirclePaint.setAntiAlias(true);//抗锯齿
        canvas.drawCircle(centre, centre, radius, mCirclePaint);//画的操作

        mArcPaint.setColor(Color.BLUE);
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setStrokeWidth(ringSize);
        RectF rectF = new RectF(centre-radius, centre - radius, centre + radius, centre + radius);
        canvas.drawArc(rectF, 90, mCurrentValue, false, mArcPaint);
        Log.i("Simon", "onDraw v:" + mCurrentValue);


        mCurrentValue = mCurrentValue % 360;
        int v = mCurrentValue * 100 / 360;//百分比
        String text = v + "%";
        float strWidth = mTextPaint.measureText(text);//获取文字长度
        mTextPaint.setColor(Color.BLUE);
        mTextPaint.setTextSize(80);
        canvas.drawText(text, centre - strWidth / 2, centre, mTextPaint);//文字居中
    }

滚动歌词

private List<String> mList = new ArrayList<>();//歌词
private Paint mTextPaint = new Paint();//歌词画笔
private int mCurrent;//第一句歌词在屏幕上的y坐标
private int mTotalHeight = 0;//歌词总的高度
private int mTextHeight;//文字高度
private Handler mHandler = new Handler();//用于页面更新

public void start(List<String> list) {
    if (list != null) {
        mList.addAll(list);

        if (mTextPaint != null) {
            Rect rect = new Rect();
            for (String str : mList) {
                mTextPaint.getTextBounds(str, 0, str.length() - 1, rect);
                mTotalHeight += rect.height();
                mTextHeight = rect.height();
            }
        }

        mCurrent = getHeight();

        mHandler.postDelayed(mRunnable, 500);
    }
}

private Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        mHandler.postDelayed(mRunnable, 1000);

        mCurrent = mCurrent - 200;
        Log.i("Simon", "" + mCurrent);
        if (mCurrent < 0) {
            int tmp = -mCurrent;
            if (tmp > mTotalHeight) {
                mCurrent = getHeight();
            }
        }
        invalidate();
    }
};

@Override
protected void onDraw(Canvas canvas) {
    for (int i = 0; i < mList.size(); i++) {
        canvas.drawText(mList.get(i), 0, mCurrent + i * mTextHeight, mTextPaint);
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width;
    int height;
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);  //宽度的测量模式
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);  //宽度的测量值
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);  //高度的测量模式
    int heightSize = MeasureSpec.getSize(heightMeasureSpec); //高度的测量值
    //如果布局里面设置的是固定值,这里取布局里面的固定值;如果设置的是match_parent,则取父布局的大小
    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;
    } else {
        //如果布局里面没有设置固定值,这里取布局的宽度的1/2
        width = widthSize * 1 / 2;
    }

    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else {
        //如果布局里面没有设置固定值,这里取布局的高度的3/4
        height = heightSize * 1 / 2;
    }

    setMeasuredDimension(width, height);
}

多TextView排列

public class CustomViewGroupActivity extends AppCompatActivity {
    private CustomViewGroup mCustomViewGroup;
    private String[] mStrArr = new String[] {
      "我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人",
      "赵铅酸",
      "我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人",
      "哈哈",
      "呵呵",
      "洗洗",
      "流苏",
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_view_group);
        mCustomViewGroup = findViewById(R.id.custom_view_group);
        findViewById(R.id.button).setOnClickListener(v -> {
//            mCustomViewGroup
            for (int i = 0; i < mStrArr.length; i++) {
                TextView tv = new TextView(this);
                tv.setText(mStrArr[i]);
                tv.setBackgroundColor(Color.RED);
                mCustomViewGroup.addView(tv);
            }
            mCustomViewGroup.requestLayout();
//            mCustomViewGroup.invalidate();
        });
    }
}

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class CustomViewGroup extends ViewGroup {
    private int padding = 10;
    private int margin = 10;

    public CustomViewGroup(Context context) {
        super(context);
    }

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

    public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int currentX = 0;
        int currentY = 0;
        int row = 1;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            child.setPadding(padding, padding, padding, padding);
            child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            int measureWidth = child.getMeasuredWidth();
            int measureHeight = child.getMeasuredHeight();

            currentX = currentX +measureWidth + margin;
            if (currentX > width - margin) {
                if (i != 0) {
                    row ++;
                    currentX = measureWidth + margin;
                }
            }
            currentY = row * (measureHeight + margin);
        }

        setMeasuredDimension(width, currentY + margin);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int width = r - l;
        int currentX = 0;
        int currentY = 0;
        int row = 1;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            int measureWidth = child.getMeasuredWidth();
            int measureHeight = child.getMeasuredHeight();

            currentX = currentX +measureWidth + margin;
            if (currentX > width - margin) {
                if (i != 0) {
                    row ++;
                    currentX = measureWidth + margin;
                }
            }

            if (currentX > width - margin) {
                currentX = width - margin;
                measureWidth = width - margin * 2;
            }

            currentY = row * (measureHeight + margin);

            child.layout(currentX - measureWidth, currentY - measureHeight, currentX, currentY);
        }
    }
}

五、事件分发

1、分发对象

MotionEvent

2、事件

MotionEvent.ACTION_DOWN
MotionEvent.ACTION_UP
MotionEvent.ACTION_MOVE
MotionEvent.ACTION_CANCEL

3、顺序

Activity->ViewGroup->View

4、重要方法

dispatchTouchEvent (MotionEvent event)进行事件分发。
onlnterceptTouchEvent(MotionEvent event)用来进行事件拦截 只有ViewGroup有
onTouchEvent(MothionEvent event);用来处理事件。

5、流程

图片.png

a. 对于 dispatchTouchEvent,onTouchEvent,return true是终结事件传递。return false 是回溯到父View的onTouchEvent方法。
b. ViewGroup 想把自己分发给自己的onTouchEvent,需要拦截器onInterceptTouchEvent方法return true 把事件拦截下来。
c. ViewGroup 的拦截器onInterceptTouchEvent 默认是不拦截的,所以return super.onInterceptTouchEvent()=return false;
d. View 没有拦截器,为了让View可以把事件分发给自己的onTouchEvent,View的dispatchTouchEvent默认实现(super)就是把事件分发给自己的onTouchEvent。

6、View和ViewGroup事件分发的区别

  1. View不包含onInterceptTouchEvent方法,事件到了View这里要么处理要么不处理
  2. ViewGroup包含onInterceptTouchEvent方法

7、View的事件分发机制和滑动冲突解决方案

参考:https://www.jianshu.com/p/057832528bdd

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

推荐阅读更多精彩内容