Android自定义view构造方法

Android自定义view

1. 自定义view的四个构造方法:

  • 第一个public View(Context context)
    这是在activity或其他中直接创建 new时,调用该构造方法,只需要传入context,所以他的属性可以根据提供的各种set***()方法去设置
  • 第二个public View(Context context, AttributeSet attrs)
    这是时当声明在xml文件中,系统在解析这个XML布局的时候调用,可以从attrs这个数组中获取在xml中声明的各种属性,
  • 第三个 public View(Context context, AttributeSet attrs, int defStyleAttrs)
    这个比第二个多出了一个defStyleAttrs,顾名思义,这是一个style,获取当前主题中声明的这个自定义view的style,所以,同个它可以实现不同主题有不同的显示效果。
    这个构造函数通常是通过第二个构造函数调用,如:
    1
    2
    3
    4
    5
    //注意,调用的是this()也就是你写的第三个构造函数 , 而不是super(),否则就不会调用你自己的第三个构造函数了

    public CircleView(Context context, @Nullable AttributeSet attrs) {
    this(context,attrs, R.attr.SimpleCircleStyle);
    }

同时通过其注释:

@param defStyleAttr An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

可看出,要想不让他通过主题里的这个view的style获取默认值,只需把他设置 defStyleAttr=0即可。
再进一步,其实第二个构造函数的实现就是调用了第三个:

1
2
3
4

public View(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
  • 第四个public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)(21)
    这个需要api21,相对于第三个多了defStyleRes,所以这是说明你可以新建一个style,然后用他去代替主题里的这个view的default style,那为什么要这样做呢?
    Theme是全局控制样式的,但是时候我们只想为某几个TextView单独定义样式,那就得使用四个参数的构造函数。
    所以你需要新建一个继承他,然后第二个构造函数调用第三个,defStyleAttr传入0,第三个构造函数再继续调用第四个,defStyleRes传入你自定义的style。

总结:

  • 其实这四个构造函数是相关联的,使用中只会直接调用第一个,或者第二个构造函数;
    第四个通过第三个调用,第三个通过第二个调用。
  • 优先顺序:不管通过哪个获取,都是一个函数:
    obtainStyledAttributes( AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
    优先顺序:

    在布局xml中直接定义 >
    在布局xml中通过style定义 >
    自定义View所在的Activity的Theme中指定style引用 >
    构造函数中defStyleRes指定的默认值

使用:

  • 添加自定义属性
    在res/values/目录下增加一个resources xml文件,示例如下(res/values/attrs_my_custom_view.xml):
    1
    2
    3
    4
    <declare-styleable name="CircleView">
    <attr name="circleColor" format="color|reference"/>

    </declare-styleable>
  • 设置在主题中的style:
    需要先声明一个attr:<attr name="SimpleCircleStyle" format="reference"/>
    然后在当前主题中为其赋值:
    <item name="SimpleCircleStyle">@style/SimpleCircleStyle</item>(值为你自定义的一个style)
  • attrs.xml文件中属性类型format值的格式
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    "reference" //引用  
    "color" //颜色
    "boolean" //布尔值
    "dimension" //尺寸值
    "float" //浮点值
    "integer" //整型值
    "string" //字符串
    "fraction" //百分数,比如200%

    //枚举类型:
    < attr name="orientation">
    < enum name="horizontal" value="0" />
    < enum name="vertical" value="1" />
    < /attr>
© 2020 WPY's Android Tour All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero