Android_(自定义view_2)

笔记是个人学习整理。
View绘制过程
View的绘制可以分为下面三个过程:
1:Measure

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {}

View类已经提供了一个基本的onMeasure实现:

   public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

MeasureSpec类是View类的一个内部静态类,它定义了三个常量UNSPECIFIED、AT_MOST、EXACTLY,其实我们可以这样理解它,它们分别对应LayoutParams中match_parent、wrap_content、xxxdp。我们可以重写onMeasure来重新定义View的宽高
2:Layout
Layout过程对于View类非常简单,同样View给我们暴露了onLayout方法

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}

3:Draw
Draw过程,就是在canvas上画出我们需要的View样式。同样View给我们暴露了onDraw方法

protected void onDraw(Canvas canvas) {
}

View中还有三个比较重要的方法
requestLayout
View重新调用一次layout过程。

invalidate
View重新调用一次draw过程

forceLayout
标识View在下一次重绘,需要重新调用layout过程。

测试:
public class DemoView extends View {
  public DemoView(Context context) {
    this(context,null);
  }
  public DemoView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }
  public DemoView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  .......
}

View有了三个构造方法需要我们重写,这里介绍下三个方法会被调用的场景,

第一个方法,一般我们这样使用时会被调用,View view = new View(context);
第二个方法,当我们在xml布局文件中使用View时,会在inflate布局时被调用,

第三个方法,跟第二种类似,但是增加style属性设置,这时inflater布局时会调用第三个构造方法。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值