Android attrs文件(自定义)属性详解

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













<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>

使用:

.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="字符串" />

获取:

package wkk.demo4;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by wkk on 2016/5/13.
 */
public class MyView extends View {


    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        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,Android,自定义View)