前言
自定義屬性的基本概念我就不寫了,可以參考這篇部落格:
http://www.cnblogs.com/whoislcj/p/5711001.html
本文主要集合一個組合控件bottombar來練習一下自定義屬性的使用。
效果圖:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmL2x2ZuNDMj1GMzoGc4JXbrdGZm1mZxkHbKFnalFjNwAzLcRjMwEzdt9CXuNmLn1Wah5Waz5iM4d3Lc9CX6MHc0RHaiojIsJye.jpg)
如何操作
step 1:res/value下邊進行attr.xml的定義:
類似;
<resources>
<declare-styleable name="NetLinearWrapContainer">
<attr name="haveActionBar" format="boolean" />
</declare-styleable>
</resources>
step 2:自定義屬性被定義了之後,在自定義控件内的讀取:
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BottomBarLayout);
if (null != typedArray) {
float mMargLeftDimension = typedArray.getDimension(R.styleable.BottomBarLayout_center_mar_left, );
float mMargRightDimension = typedArray.getDimension(R.styleable.BottomBarLayout_center_mar_right, );
LinearLayout.LayoutParams layoutParams = (LayoutParams) mRd_phone.getLayoutParams();
layoutParams.setMargins((int) mMargLeftDimension, layoutParams.topMargin, (int) mMargRightDimension, layoutParams.bottomMargin);
mRd_phone.setLayoutParams(layoutParams);
}
step 3:XML布局檔案内,命名空間的定義:
注意這個app也可以自己定義成其他的字元串,比如:
step 4:XML布局檔案内,屬性的使用:
或者
總結
注意這些屬性是需要事先定義在attrs.xml内的
另外讀取它時,是需要加上字首,
比如這裡的R.styleable.BottomBarLayout_center_mar_right
字首就是BottomBarLayout_,它是根據attrs内的屬性名來的。
還有一個比較難了解的地方是,自定義屬性的種類繁雜,不同的種類讀取值的api也不盡相同。
Demo
本文demo