如何使用自定義屬性

1.預(yù)習(xí):

Android自定義控件之自定義屬性 format詳解

2.在attrs.xml中創(chuàng)建自定義屬性

Paste_Image.png

其中:

3.在自定義View中獲取xml中設(shè)置的自定義屬性

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"/>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,323評論 25 708
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,380評論 0 17
  • 感賞:感賞我的家鄉(xiāng)在這萬物復(fù)蘇的季節(jié),呈現(xiàn)出蓬勃生機,日新月異,萬象更新,一切都變得美好起來!大家都在憧憬新特區(qū)的...
    半笑人生閱讀 184評論 0 0
  • 現(xiàn)如今iOS開發(fā)也迎來了各種尺寸的屏幕,5.5、4.7、4、3.5。面對如此問題,Apple公司也在不停的迭代UI...
    invokefear閱讀 1,322評論 1 2
  • 2016年已經(jīng)進入了倒計時,四天之后,我們將別無選擇的進入2017,從1987到2017,我也將迎來30而立。而立...
    和一波閱讀 403評論 0 2

友情鏈接更多精彩內(nèi)容