在開發中有時候我們需要去自定義一些組合控件,而在使用過程中,又想要自己的組合控件能有原生控件那樣可以在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"
4:最後說一點的就是,在attrs文件中styleable中的命名是可以自定義的,但是爲了在書寫佈局文件時有屬性的提示功能,所以最好還是保持自定義控件的類名與styleable的命名一致,當然,Google也支持和鼓勵開發者使用對應的類名來作爲styleable的命名