android 自定义view参数,Android自定义View中,四个参数的构造函数的含义

MyView(Context context)

Used when instanciating Views programmatically.

MyView(Context context, AttributeSet attrs)

Used by the LayoutInflater to apply xml attributes. If one of this attribute is named style, attributes will be looked up the the style before looking for explicit values in the layout xml file.

MyView(Context context, AttributeSet attrs, int defStyleAttr)

Suppose you want to apply a default style to all widgets without having to specify style in each layout file. For an example make all checkboxes pink by default. You can do this with defStyleAttr and the framework will lookup the default style in your theme.

Note that defStyleAttr was incorrectly named defStyle some time ago and there is some discussion about whether this constructor is really needed or not. See https://code.google.com/p/android/issues/detail?id=12683

MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

The 3rd constructor works well if you have control over the base theme of the applications. That is working for google because they ship their widgets along side the default Themes. But suppose you're writing a widget library and you want a default style to be set without your users needing to tweak their theme. You can now do this using defStyleRes by setting it to the default value in the 2 first constructors:

public MyView(Context context) {

super(context, null, 0, R.style.MyViewStyle);

init();

}

public MyView(Context context, AttributeSet attrs) {

super(context, attrs, 0, R.style.MyViewStyle);

init();

}

All in all

If you're implementing your own views, only the 2 first constructors should be needed and can be called by the framework.

If you want your Views to be extensible, you might implement the 4th constructor for children of your class to be able to use global styling.

I don't see a real use case for the 3rd constructor. Maybe a shortcut if you don't provide a default style for your widget but still want your users to be able to do so. Shouldn't happen that much.

文章来源: www.oschina.net,作者:SuShine,版权归原作者所有,如需转载,请联系作者。

原文链接:https://my.oschina.net/sfshine/blog/3108621

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值