attrs 资源文件 自定义属性

原文:https://blog.csdn.net/w18756901575/article/details/51396405

在res/values文件夹下新建attrs.xml文件:

<!-- declare-styleable表示为自定义的属性-->
<!-- format表示为可接受的参数类型-->
<!--integer int型-->
<!--boolean boolean-->
<!--color 颜色-->
<!--dimension 尺寸-->
<!--enum 枚举-->
<!--flag 位或运算-->
<!--float float型-->
<!--fraction 百分数-->
<!--reference 资源文件-->
<!--string 字符串-->
<declare-styleable name="MyView">
    <attr name="a" format="integer"></attr>
    <attr name="b" format="boolean"></attr>
    <attr name="c" format="color"></attr>
    <attr name="d" format="dimension"></attr>
    <attr name="e"></attr>
    <attr name="f"></attr>
    <attr name="g" format="float"></attr>
    <attr name="h" format="fraction"></attr>
    <attr name="i" format="reference"></attr>
    <attr name="j" format="string"></attr>
</declare-styleable>
<attr name="e">
    <enum name="e1" value="1"></enum>
    <enum name="e2" value="2"></enum>
</attr>
<attr name="f">
    <flag name="f1" value="1"></flag>
    <flag name="f2" value="2"></flag>
</attr>

使用:

<wkk.demo4.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:a="1"
app:b="true"
app:c="#ffffff"
app:d="20dp"
app:e="e1"
app:f="f1|f2"
app:g="0.1"
app:h="100%"
app:i="@mipmap/ic_launcher"
app:j="字符串" />

获取:

 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        int a = typedArray.getInt(R.styleable.MyView_a, 0);
        boolean b = typedArray.getBoolean(R.styleable.MyView_b, true);
        int c = typedArray.getColor(R.styleable.MyView_c, 0x00000000);
        int d = typedArray.getDimensionPixelSize(R.styleable.MyView_d, 0);
        int e = typedArray.getInt(R.styleable.MyView_e, 0);
        int f = typedArray.getInt(R.styleable.MyView_f, 0);
        float g = typedArray.getFloat(R.styleable.MyView_g, 0.1f);
        String h = typedArray.getString(R.styleable.MyView_h);
        int i = typedArray.getResourceId(R.styleable.MyView_i, -1);
        String j = typedArray.getString(R.styleable.MyView_j);
        typedArray.recycle();

获取原来android的src属性:

public MyGif(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        int image = attrs.getAttributeResourceValue( "http://schemas.android.com/apk/res/android", "src", 0);
        movie = Movie.decodeStream(getResources().openRawResource(image));
    }
原文地址:https://www.cnblogs.com/zhaozilongcjiajia/p/10823644.html