(一)自定义之---自定义属性

一,基本使用,

1,在res-values文件夹下新建attrs.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--declare-styleable: 表示一个属性组。它的name必须和你自定义view的名字相同-->
    <declare-styleable name="CustomeCircle">
        <!--attr:表示单独的一个属性。format代表属性的格式-->
        <attr name="circle_color" format="color"></attr>
    </declare-styleable>
</resources>


2,新建一个自定义类,通过obtainStyledAttributes设置属性值,但记得recycle(),用完回收,

public class CustomeCircle extends View {

    private Paint mPaint = new Paint();


    public CustomeCircle(Context context) {
        this(context,null);
    }


    public CustomeCircle(Context context,  AttributeSet attrs) {
        this(context,attrs,0);
    }

    public CustomeCircle(Context context,  AttributeSet attrs, int defStyleAttr ) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomeCircle);
        int color = typedArray.getColor(R.styleable.CustomeCircle_circle_color, Color.RED);
        typedArray.recycle();
        mPaint.setColor(color);
    }


3,也可以在layout.xml布局中使用该属性

<laobi.com.customecircledemo.CustomeCircle
    android:visibility="visible"
    android:layout_margin="10dp"
    android:padding="10dp"
    android:layout_width="wrap_content"
    app:circle_color="#00ffff"
    android:layout_height="100dp"
    android:background="#000"/>

二,相关属性:

(一)属性值的类型(format)有如下几种:

         1,boolean 表示attr取值为true或者false

         2,olor 表示attr取值是颜色类型,例如#ff3344,或者是一个指向color的资源id,例如R.color.colorAccent.

扫描二维码关注公众号,回复: 2515771 查看本文章

      3,dimension 表示 attr 取值是尺寸类型,例如例如取值16sp、16dp,也可以是一个指向dimen的资源id,例如R.dimen.dp_16

        4,float 表示attr取值是整形或者浮点型

        5,raction 表示 attr取值是百分数类型,只能以%结尾,例如30%

        6,integer 表示attr取值是整型

        7,string 表示attr取值是String类型,或者一个指向String的资源id,例如R.string.testString

        8,reference 表示attr取值只能是一个指向资源的id。

        9,enum 表示attr取值只能是枚举类型。

        10,flag 表示attr取值是flag类型。


猜你喜欢

转载自blog.csdn.net/qq_38859786/article/details/80692201