自定义属性步骤

2019-04-28  本文已影响0人  StoneWay3

第一步:创建属性文件attrs.xml

位置:res -> values ->new xml ->attrs.xml

声明一个名字

声明具体的属性

属性值的类型简单介绍(format)

1.reference 引用类型值:@+id/……等

2.color 颜色类型值 #FFFFFF 

3.boolean 布尔类型 true和false 

4.dimension 尺寸类型值 dp/sp/dip/px/pt等

5.integer 整数类型值 progress max weight,R.color.xx等等

6.float 小数类型 0.1f,1.3f等

7.string 字符类型 "text" 等

8.<enum> 枚举类型 水平,垂直,居中等等

<?xml version="1.0" encoding="utf-8"?>

    <declare-styleable name="RoundProgressBar">

        <attr name="roundColor" format="color"/>

        <attr name="roundProBarColor" format="color"/>

        <attr name="textColor" format="color"/>

        <attr name="roundWidth" format="dimension"/>

        <attr name="textSize" format="dimension"/>

        <attr name="progress" format="integer"/>

        <attr name="proBarMax" format="integer"/>

</resources>

第二步:在布局文件中引用当前的命名空间

其中app是系统自动生成的,也可以随意自定义

xmlns:app="http://schemas.android.com/apk/res-auto"

第三步:在自定义控件中使用自定义的属性

app:roundColor="@color/colorPrimary"

第四步:在自定义控件的构造器中,引用自定义的属性

//获取自定义的属性

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar);

//取出所有的自定义属性

roundColor = typedArray.getColor(R.styleable.RoundProgressBar_roundColor, Color.GRAY);

roundProBarColor = typedArray.getColor(R.styleable.RoundProgressBar_roundProBarColor, Color.RED);

textColor = typedArray.getColor(R.styleable.RoundProgressBar_textColor, Color.RED);

roundWidth = typedArray.getDimension(R.styleable.RoundProgressBar_roundWidth, UiUtils.dp2px(10));

textSize = typedArray.getDimension(R.styleable.RoundProgressBar_textSize, UiUtils.dp2px(20));

proBarMax = typedArray.getInteger(R.styleable.RoundProgressBar_proBarMax, 100);

progress = typedArray.getInteger(R.styleable.RoundProgressBar_progress, 33);

//回收处理

typedArray.recycle();

上一篇 下一篇

猜你喜欢

热点阅读