android自定义View构造方法以及获取自定义属性详解

首先View有三个构造方法,如下:

  • View(Context context)
    Simple constructor to use when creating a view from code.
    View(Context context,AttributeSet attrs)
    Constructor that is called when inflating a view from XML.
    View(Context context,AttributeSet attrs, int defStyle)
    Perform inflation from XML and apply a class-specific base style.
第一个构造方法很简单,就是通过代码创建时才使用。下面主要详细介绍第二个和第三个。

第二个构造方法:

它的说明也就是:当我从xml中加载view的时候,这个构造器才会被调用。其第二个参数中就包含自定义的属性。 接下来讲解自定义属性:
 

自定义属性用法第一步:

在value文件夹中新建一个xml文件,文件名可以随意取,不过一般定义成attrs。在其中用到两个标签,例如:
<declare-styleable name="CustomView">
        <attr name="txt" format="string"/>
        <attr name="android:background"/>
        <attr name="android:textColor"/>
    </declare-styleable>
关于这些标签的用法可参照 http://blog.csdn.net/dalancon/article/details/9701855
自定义属性用法第二步:
TypedArray type = context.obtainStyledAttributes(attrs, R.styleable.CustomView);获得TypeArray后,从其中得到值
int color = type.getColor(R.styleable.CustomView_android_textColor,Color.RED);
最后 TypedArray  通常最后调用  .recycle()  方法,为了保持以后使用该属性一致性!

第三个构造方法View(Context context, AttributeSet attrs, int defStyle)

Perform inflation from XML and apply a class-specific base style.从xml加载时执行和应用一个特定的风格。这里有两种方式,一是冲theme中获得,二是从style中获得。
        第三个参数官方有这样的说明:
  • defStyle - The default style to apply to this view. If 0, no style will be applied (beyond what is included in the theme). This may either be an attribute resource, whose value will be retrieved from the current theme, or an explicit style resource.
默认的风格去应用到这个view上。如果是0,没有风格将会被应用(除了被包含在主题中)。这个也许是一个属性的资源,它的值是从当前的主题中检索,或者是一个明确的风格资源。
1.从主题中获取:
在attrs中定义一个属性<attr name=" CustomStyle" format="reference"/>,也就是这个属性会参照一个style。
activity中定义主题:android:theme="@style/StyledIndicators"  ,这个StyledIndicators中包含 <item name=" CustomStyle">@style/CustomIndicator</item>,attrs中的属性在CustomIndicator中写值
<style name="CustomIndicator">
        <item name="android:background">#18FF0000</item>
        <item name="android:textColor">#AA006600</item>
    </style>
然后在代码中
public CustomView(Context context, AttributeSet attrs) {
// TODO Auto-generated constructor stub
this(context,attrs,R.attr.CustomStyle);
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
TypedArray type = context.obtainStyledAttributes(attrs,R.styleable.CustomView,defStyleAttr,0);
接下来就跟第二个构造方法中做的一样了

2.从风格中获取:
this(context,attrs,R.style.CustomIndicator);TypedArray type = context.obtainStyledAttributes(attrs,R.styleable.CustomView,0,defStyleAttr);
接下来就跟第二个构造方法中做的一样了。











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值