自定义View-----笔记

OnDraw()绘制
view绘制是从画布的左上角为原点开始绘制的
canvas.drawRect(left,top,right,bottom, paint);
//left矩形左边离屏幕左距离 top矩形上边离屏幕上距离 right矩形右边离屏幕左距离 bottom矩形下边离屏幕上距离
1、绘制区域
2、 invalidate(),postInvalidate()
3、Canvas.drawxxx
4、translate、rotate、scale、skew.
5、save() ,restore()

状态的保存与恢复

1、onSaveInstanceState //保存状态
2、onRestoreInstanceState //恢复状态

    protected Parcelable onSaveInstanceState()
    {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE_STATUS,super.onSaveInstanceState());
        bundle.putFloat(STATUS_ALPHA,mAlpha);
        return bundle;
    }
    protected void onRestoreInstanceState(Parcelable state)
    {
        if(state instanceof Bundle){
            Bundle bundle = (Bundle) state;
             mAlpha = bundle.getFloat(STATUS_ALPHA);

            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATUS));
            return;
        }
        super.onRestoreInstanceState(state);
    }

测量onMeasure

1、三个测量模式:EXACTLY(用户声明具体的值),AT_MOST(可以自己设置值,但不能超过父控件给你的值) ,UNSPECIFIED(不限定大小)

2、MeasureSpec (此类下的方法可以获取到父控件传过来三种模式中的哪一种,传人的值的大小等)

3、setMeasuredDimension() (此方法用来设定View测量后的宽度高度)

4、requestLayout()(此方法可以在View的大小发生改变的时候强制再次进行测量大小)

private int measureHeight(int heightMeasureSpec)
    {
        int result = 0;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);
        if(mode == MeasureSpec.EXACTLY)
        {
            result = size;
        }else
        {
            result =  getMeasuredHeight() + getPaddingTop()
            +getPaddingBottom();//计算自身需要的高度
            if(mode == MeasureSpec.AT_MOST)
            {
                result = Math.min(result,size);
            }
        }
        return result;
    }

自定义属性:
values文件夹下新建一个.xml文件 名字可自定义,一般使用attrs
在.xml文件中的中使用:

<declare-styleable name="MyView">
    <attr name="viewColor" format="color"/>
</declare-styleable>

format还可以指定其他的类型比如;
reference 表示引用,参考某一资源ID
string 表示字符串
color 表示颜色值
dimension 表示尺寸值
boolean 表示布尔值
integer 表示整型值
float 表示浮点值
fraction 表示百分数
enum 表示枚举值
flag 表示位运算

其中attr为自定义属性。
然后在使用到自定义view的地方为我们的自定义属性赋值

<com.l.sqlhelperdemo.MyView
    app:viewColor="@color/colorPrimary"//自定义属性
    android:layout_width="match_parent"
    android:layout_height="150dp"/>

接下来在自定义的View类中获取自定义属性的数据

private ColorStateList mColorStateList;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);//创建TypeDArray对象
 mColorStateList = typedArray.getColorStateList(R.styleable.MyView_viewColor);//获取自定义属性的数据
typedArray.recycle();//回收

然后将我们获取到的自定义属性的数据用到onDraw()方法中就可以了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值