自定义View之构造函数学习

在学习了博客里前辈们的关于自定义View知识,来总结一下我学习自定义View构造函数的收获,以及还有遇到的一些问题。遇到的问题,在以后解决后,会补充。

开始做一件事情,不要求自己一步做到完美,我会慢慢改进学习,去完善。

问题,驱动学习!


一、自定义View构造函数。

一共有四个构造函数,关于有四个参数的构造函数,是在Android API 21 之后才添加的。(AndroidL的新特性)

public class CustonViewComstructorStudy extends View {
    /**在Java代码中,new一个View时候,通常使用*/
    public CustonViewComstructorStudy(Context context) {
        super(context);
    }

    /**在xml中引入一个视图View时,这个View是我们自己定义在xml布局文件当中。
     * 官方文档:Constructor that is called when inflating a view from XML.*/
    public CustonViewComstructorStudy(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**在打印日志里,始终没有看到程序走第三个构造函数*/
    public CustonViewComstructorStudy(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**基于Android API 21之后*/
    public CustonViewComstructorStudy(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
}


通过Android source可以看到,第二个,第三个构造函数都是调用了四个参数的构造函数,参数默认补0;


二、添加自定义属性,给要操作的自定义View使用。(这些自定义属性都是针对两个,或者两个以上参数的构造函数使用。)

1、在res目录下,values文件内,新建一个attrs.xml。

通过<declare-styleable>标签内的子标签<attr>,添加View的自定义属性。

<attr name="填写属性名称" format="属性类型">

代码a attr.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--这里是我们自己写的内容,declare-styleable 的name默认提示与自定义View的类名一致-->
    <declare-styleable name="CustomViewStudy">
        <attr name="attr_string1" format="string"/>
        <attr name="attr_integer2" format="integer"/>
        <attr name="attr_boolean3" format="boolean"/>
        <attr name="attr_float4" format="float"/>
        <attr name="attr_color5" format="color"/>
        <attr name="attr_string6" format="string"/>
        <attr name="android:text"/>
        <attr name="android:textSize"/>

    </declare-styleable>


    <attr name="customize_reference" format="reference"/>
</resources>
解释说明:
关于format的属性类型,参看博客:http://blog.csdn.net/mybeta/article/details/39962235  自定义View属性。

关于<atte name="customize_refernce" format="reference">也可以在<declare-styleable>标签内,或者标签外。移动位置以后,需要clean下代码。任意一条属性都可以。

2、随即,一个问题来,<declare-styleable>标签的作用是什么?

首先不管是否使用<declare-styleable>,系统都会在R.attr中生成他们对应的attribute值。

public static final int customize_reference=0x7f010000;
如果使用了该标签,系
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值