自定义View(1)——构造方法与参数传递

        在自定义View的过程中,最先需要了解View的四种构造方法的使用条件以及参数。

        四种构造方法如下:

    /**
     * 使用代码 new 创建时使用
     */
    public StatusBar(Context context) {
        this(context, null);
    }

    /**
     * 使用布局文件加载时使用
     * @param context
     * @param attrs 布局文件参数
     */
    public StatusBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
//        this(context, attrs, R.style.Base_Theme_AppCompat_Light); // 显示的调用构造方法
    }

    /**
     * 使用默认style 只有明确调用时才生效
     * @param context
     * @param attrs 布局文件参数
     * @param defStyleAttr activity 或 application 的风格
     */
    public StatusBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // 初始化控件
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar);
        typedArray.recycle();
        init();
    }

    /**
     * 最小 API21 使用  目前没有实际用途
     * @param context
     * @param attrs
     * @param defStyleAttr
     * @param defStyleRes
     */
    public StatusBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context);
    }</span>

    首先需要在 res/values/attrs.xml 文件中如下配置:

    <declare-styleable name="StatusBar">
        <attr name="type" format="string" />
        <attr name="greenColor" format="color" />
        <attr name="grayColor" format="color" />
        <attr name="textGreenColor" format="color" />
        <attr name="textGrayColor" format="color" />
        <attr name="textSize" format="integer"/>
    </declare-styleable></span>
 
    使用 declare-styleable 声明风格,使用attr 来声明具体的参数。 

    xml中需要使用自定义View的属性,需要声明命名空间,然后直接使用属性:

xmlns:app="http://schemas.android.com/apk/res-auto"
    <com.example.administrator.mydemo.widget.StatusBar
        android:id="@+id/bar"
        app:textSize="14"
        app:textGreenColor="#fff000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" /></span>
     在构造方法代码中接收传递的参数:

public StatusBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // 初始化控件
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar);
        this.textsize = typedArray.getInteger(R.styleable.StatusBar_textSize,14);
        this.finishTextColor = typedArray.getColor(R.styleable.StatusBar_textGreenColor,Color.RED);
        // 释放资源
        typedArray.recycle();
        init();
    }
 

    通过参数Attributes将传递的参数一一解析,最后不要忘了释放TypeArray资源。

    最后跟上这个Demo的GitHub地址:GitHub简单自定义View Demo地址 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值