前言
自定义属性的基本概念我就不写了,可以参考这篇博客:
http://www.cnblogs.com/whoislcj/p/5711001.html
本文主要集合一个组合控件bottombar来练习一下自定义属性的使用。
效果图:
如何操作
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, 0);
float mMargRightDimension = typedArray.getDimension(R.styleable.BottomBarLayout_center_mar_right, 0);
LinearLayout.LayoutParams layoutParams = (LayoutParams) mRd_phone.getLayoutParams();
layoutParams.setMargins((int) mMargLeftDimension, layoutParams.topMargin, (int) mMargRightDimension, layoutParams.bottomMargin);
mRd_phone.setLayoutParams(layoutParams);
}
step 3:XML布局文件内,命名空间的定义:
xmlns:app="http://schemas.android.com/apk/res-auto"
注意这个app也可以自己定义成其他的字符串,比如:
xmlns:nba="http://schemas.android.com/apk/res-auto"
step 4:XML布局文件内,属性的使用:
app:haveActionBar = "true"
或者
nba:haveActionBar = "true"
总结
注意这些属性是需要事先定义在attrs.xml内的
另外读取它时,是需要加上前缀,
比如这里的R.styleable.BottomBarLayout_center_mar_right
前缀就是BottomBarLayout_,它是根据attrs内的属性名来的。
还有一个比较难理解的地方是,自定义属性的种类繁杂,不同的种类读取值的api也不尽相同。