如何使用自定义属性

2016-12-09  本文已影响0人  饥人谷_js_chen

1.预习:

Android自定义控件之自定义属性 format详解

2.在attrs.xml中创建自定义属性

Paste_Image.png

其中:

3.在自定义View中获取xml中设置的自定义属性

public class CustomTextView extends TextView {
    public CustomTextView(Context context) {
        this(context, null);
    }

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

    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.anything);
        String attr_str = typedArray.getString(R.styleable.anything_attr_str);
        Integer attr_integer = typedArray.getInteger(R.styleable.anything_attr_integer, -1);
        Drawable attr_backgroud = typedArray.getDrawable(R.styleable.anything_attr_background);
        int attr_color = typedArray.getColor(R.styleable.anything_attr_color, 0);
        boolean attr_boolean = typedArray.getBoolean(R.styleable.anything_attr_boolean, false);
        setText(attr_str + ", " + attr_integer + ", " + attr_boolean);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) {//>=16
            setBackground(attr_backgroud);
        } else {
            setBackgroundDrawable(attr_backgroud);
        }
        setTextColor(attr_color);
    }
}

4.在布局文件中为自定义属性赋值

<along.chen.com.myview.CustomTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:attr_str="It's just a next beginning"
            app:attr_boolean="true"
            app:attr_color="#f00a"
            app:attr_background="@drawable/shape_backgroud"
            android:padding="15dip"
            android:text="@string/app_name"/>
上一篇下一篇

猜你喜欢

热点阅读