一、属性介绍
format格式类型
"reference" //引用
"color" //颜色
"boolean" //布尔值
"dimension" //尺寸值
"float" //浮点值
"integer" //整型值
"string" //字符串
"fraction" //百分数,比如200%
枚举型的格式: format的格式,视value的值而定
< attr name="attrtest">
< enum name="horizontal" value="0" />
< enum name="vertical" value="1" />
< /attr>
标志位、位或运算,格式如下
< attr name="windowSoftInputModeTest">
< flag name = "stateUnspecified" value = "0" />
< flag name = "stateUnchanged" value = "1" />
< flag name = "stateHidden" value = "2" />
< flag name = "stateAlwaysHidden" value = "3" />
< flag name = "stateVisible" value = "4" />
< flag name = "stateAlwaysVisible" value = "5" />
< flag name = "adjustUnspecified" value = "0x00" />
< flag name = "adjustResize" value = "0x10" />
< flag name = "adjustPan" value = "0x20" />
< flag name = "adjustNothing" value = "0x30" />
< /attr>
二,attr文件的创建,以及在布局文件xml中的使用
以洪洋大神的FloatLayout举例:
参考链接:https://github.com/hongyangAndroid/FlowLayout/
1、在资源文件夹(values)中新建文件名称为 attr.xml 的资源文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TagFlowLayout">
<attr name="max_select" format="integer"></attr>
<attr name="tag_gravity">
<enum name="left" value="-1" />
<enum name="center" value="0" />
<enum name="right" value="1" />
</attr>
</declare-styleable>
</resources>
2、在布局文件xml中,使用自定义属性
<com.zhy.view.flowlayout.TagFlowLayout
android:id="@+id/id_flowlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="20dp"
zhy:max_select="-1"
app:tag_gravity="center"
/>
此时,app为自己定义的命名空间,可快捷键生成,app随意写即可,后面会自动找到,也可以条件manifest里面添加包名,一般采用如下:
xmlns:app="http://schemas.android.com/apk/res-auto"
app:tag_gravity="center",
zhy为鸿神的命名空间
zhy:max_select="-1"
三、自定义View中的解析,获取布局文件中传入的参数值。
public FlowLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TagFlowLayout);
mGravity = ta.getInt(R.styleable.TagFlowLayout_tag_gravity, LEFT);
int layoutDirection = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault());
if (layoutDirection == LayoutDirection.RTL) {
if (mGravity == LEFT) {
mGravity = RIGHT;
} else {
mGravity = LEFT;
}
}
ta.recycle();
}
猜测因为继承的ViewGroup所以自定义属性,展示view的位置
如还可以继续解析
int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
float max_select= a.getInt(R.styleable.TagFlowLayout_max_select, 1);
网友评论