Android自定義控件封裝之自定義屬性的實現


在開發中有時候我們需要去自定義一些組合控件,而在使用過程中,又想要自己的組合控件能有原生控件那樣可以在xml中使用屬性控制,那麼我們就需要去自定義一些屬性了

1:首先在values/attrs.xml中進行屬性的定義

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyAppTitle">
        <attr name="TitleText" format="string"/>
        <attr name="LeftText" format="string"/>
        <attr name="RightText" format="string"/>
    </declare-styleable>
    
</resources>

2:在定義好這些屬性後,就需要在自己自定義的類中進行獲取和操作了

public MyAppTitle(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyAppTitle);
    mLeftText = ta.getString(R.styleable.MyAppTitle_LeftText);
    mTitleText = ta.getString(R.styleable.MyAppTitle_TitleText);
    mRightText = ta.getString(R.styleable.MyAppTitle_RightText);
    Log.e("Fizzer",mLeftText+mRightText+mTitleText);
}

3:接下來就可以在xml文件佈局中進行使用了

<com.fizzer.anbangproject_dahuo_test.Widget.MyAppTitle
    android:id="@+id/viewMyAppTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    fizzer:TitleText="標題"
    fizzer:LeftText="左邊"
    fizzer:RightText="右邊"/>


還有一點要注意的就是,別忘了在根佈局中進行命名空間的聲明

xmlns:fizzer="http://schemas.android.com/apk/res-auto"


命名空間的名字是可以自定義的,比如文中的“fizzer”,開發者可以自己自行定義,但是在xml文件使用中一定要使用自己定義的命名


4:最後說一點的就是,在attrs文件中styleable中的命名是可以自定義的,但是爲了在書寫佈局文件時有屬性的提示功能,所以最好還是保持自定義控件的類名與styleable的命名一致,當然,Google也支持和鼓勵開發者使用對應的類名來作爲styleable的命名




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章