自定义View实现

    xiaoxiao2021-03-25  11

    Android自定义View

    自定义View的属性

    新建attr.xml 在其中声明我们自定义的View的属性和整个样式,标签为,其中每一个item 有name 和format两个属性

    常用的format属性有 string,color,demension,integer,enum,reference,boolean,fraction,flag

    在布局中声明我们的自定义view及其属性引用

    记得要引入我们自己的命名空间,后面的包路径指的是项目的package,也可以选为Auto.

    创建自定义View extends View,在其构造方法中获得我们的自定义属性各项值,以自定义正弦波动曲线View为例

    TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,R.styleable.WaveLineView,defStyleAttr,R.style.def_waveline_style); int indexCount = typedArray.getIndexCount(); for (int i = 0; i < indexCount; i++) { int attr = typedArray.getIndex(i); switch (attr) { case R.styleable.WaveLineView_wave_first_color: waveFirstColor = typedArray.getColor(attr, Color.BLACK); break; case R.styleable.WaveLineView_wave_second_color: waveSecondColor = typedArray.getColor(attr, Color.BLACK); break; case R.styleable.WaveLineView_wave_line_width: waveLineWidth = typedArray.getDimensionPixelSize(attr, 0); break; default: break; } } typedArray.recycle();

    函数obtainStyledAttributes()第二个参数是我们自定义的view属性的名字,第四个参数是我们自定义的包含了view属性及其取值的style,即当我们没有在布局声明中设置对应的属性时,就会从我们定义的默认style中去找属性和值。

    重写几个重要的方法,也是自定义View的精髓所在。

    通过重写onMeasure()方法我们可以拿到当前组件的大小并去设置他的大小,通过onDraw()方法我们可以在当前view中随意绘制,实现自定义view的格局样式。

    要注意的一点是:

    onMeasure()中要拿到view的宽高时

    当我们设置明确的宽度和高度 时,系统帮我们测量的结果就是我们设置的结果;

    当我们设置为 WRAP_CONTENT,或者 MATCH_PARENT 系统帮我们测量的结果就是MATCH_PARENT的长度。

    所以,当设置了WRAP_CONTENT时,我们需要自己进行测量,即重写onMesure()

    重写之前先了解MeasureSpec的specMode,一共三种类型:

    EXACTLY:一般是设置了明确的值或者是MATCH_PARENTAT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENTUNSPECIFIED:表示子布局想要多大就多大,很少使用
    转载请注明原文地址: https://ju.6miu.com/read-149589.html

    最新回复(0)