美文网首页
自定义属性

自定义属性

作者: woochen123 | 来源:发表于2017-08-02 15:02 被阅读0次

1.在res/values文件下添加一个attrs.xml文件(文件名可以自己定义)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="LoadingLayout">
         <!--添加属性-->
        <attr name="sex" />
        <attr name="color" />
    </declare-styleable>

</resources>

2.自定义属性类型

    <declare-styleable name="LoadingLayout">
       <attr name="percent_circle_gravity"><!--圆形绘制的位置-->
            <flag name="left" value="0" />
            <flag name="top" value="1" />
            <flag name="center" value="2" />
            <flag name="right" value="3" />
            <flag name="bottom" value="4" />
        </attr>
        <!-- 错误布局图片 -->
        <attr name="llErrorImage" format="reference"/>
        <!-- 错误布局文本 -->
        <attr name="llErrorText" format="string"/>
        <!-- 错误布局重试按钮文本 -->
        <attr name="llRetryText" format="string"/>
        <!-- 文本颜色 -->
        <attr name="llTextColor" format="color"/>
        <!-- 文本尺寸 -->
        <attr name="llTextSize" format="dimension"/>
        <!-- 按钮文本颜色 -->
        <attr name="llButtonTextColor" format="color"/>
        <!-- 按钮文本尺寸 -->
        <attr name="llButtonTextSize" format="dimension"/>
        <!-- 按钮背景 -->
        <attr name="llButtonBackground" format="reference"/>
    </declare-styleable>

属性类型

reference:引用资源
string:字符串
Color:颜色
boolean:布尔值
dimension:尺寸值
float:浮点型
integer:整型
fraction:百分数
enum:枚举类型
flag:位或运算

3.在布局中使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:chen="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.woochen123.views.LoadingLayout
        android:layout_width="200dp"
        android:layout_height="200dp"
        chen:llTextColor="#333333"
        chen:percent_circle_gravity="top"
        chen:llButtonTextColor="#111558" />

</LinearLayout>

4.在自定义控件中获取属性值

R.styleable.LoadingLayout_属性名

  TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LoadingLayout);
    if (typedArray != null) {
        textColor= typedArray.getColor(R.styleable.LoadingLayout_llTextColor, Color.GRAY);
        buttonTextColor = typedArray.getColor(R.styleable.LoadingLayout_llButtonTextColor, Color.BLUE);
        gravity = typedArray.getInt(R.styleable.LoadingLayout_percent_circle_gravity, CENTER);
        typedArray.recycle();
     }

相关文章

网友评论

      本文标题:自定义属性

      本文链接:https://www.haomeiwen.com/subject/mtaelxtx.html