Android中的View全解析(二)

View的内容大致分为一下四项:

View的绘制原理,

View的自定义属性,

View的生命周期,

View的事件分发机制


下面来讲一讲View的自定义属性。我们在自定义VIew的过程中,会为VIew分配许多自定义的属性,这时候,android命名空间已经无法满足我们的要求,我们就需要自己来设置命名空间。

首先,我们在values文件夹中新建一个xml文件,在其中定义VIew的属性。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ProgressBar">
        <attr name="progress" format="fraction"/> <!--当前进度-->
        <attr name="progresscolor" format="color"/> <!--进度条显示颜色-->
        <attr name="backgroundcolor" format="color"/> <!--进度条背景显示颜色-->
        <attr name="aroundcolor" format="color"/> <!--进度条包围框显示颜色-->
        <attr name="verticallength" format="fraction"/> <!--纵向进度条占比-->
        <attr name="horizontallength" format="fraction"/> <!--横向进度条占比-->
    </declare-styleable>
</resources>
使用<declare-styleable>标签定义了命名为"ProgressBar"域的一组属性。这里的域name一般设置为自定义的View的类名,当然也可以随便定义,不使用<declare-styleable>标签也是可以的。

接下来<attr>标签中定义了View的属性,name自然为属性的名字,也可以随便定义,只要自己可以识别就好。format为属性的类型,分为如下几类:

fraction 百分数

dimension  尺寸

float  浮点数

integet  整数

boolean true/false

enum 枚举

flag

reference

string 字符串

接下来,在布局文件中声明命名空间

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:yxy="http://schemas.android.com/apk/res-auto"
自定义属性的命名空间在gradle中均写为
"http://schemas.android.com/apk/res-auto"
前面的name自己定义就可以了,然后就可以向使用android命名空间一样来使用我们自定义的命名空间了。

在我们自定义的View的构造方法中,可以使用TypedArray来获取我们设定的属性。

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProgressBar);
        if (typedArray != null) {
            backgroundcolor = typedArray.getColor(R.styleable.ProgressBar_backgroundcolor, Color.GRAY);
            progresscolor = typedArray.getColor(R.styleable.ProgressBar_progresscolor, Color.WHITE);
            aroundcolor = typedArray.getColor(R.styleable.ProgressBar_aroundcolor, Color.BLUE);
            progress = typedArray.getFraction(R.styleable.ProgressBar_progress, 1, 1, 0);
            verticallength = typedArray.getFraction(R.styleable.ProgressBar_verticallength, 1, 1, 0.8f);
            horizontallength = typedArray.getFraction(R.styleable.ProgressBar_horizontallength, 1 , 1, 0.98f);
            typedArray.recycle();
        }
使用context.obtainStyledAttributes方法来获取自定义的属性数组,然后以不同属性类型的get方法来获取属性。详细的API说明,可参考 TypedArray
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值