LinearLayout的orientation
orientation是支持横向和竖向的,且是直接写在布局里面的,那么我们自定义的话是怎么来实现呢?这里就要延伸出一个自定义属性的东西。
使用步骤
在attr.xml里面配置
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MineLineLayout">
<attr name="android:orientation" format="integer">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
</resources>
这里面有format的类型有如下几个:
format类型 | 说明 |
---|---|
boolean | attr是布尔类型的值,取值只能是true或false |
string | string类型 |
integer | int整型(不含浮点型) |
float | 浮点型(包含整型) |
fraction | 表示百分数,只能以%号结尾 |
color | 代表颜色,可以使用#000000,也可以使用@color/white |
dimension | 代表attr是尺寸类型.px/dp/sp结尾都可 |
reference | attr的值只能指向某一资源的ID |
enum | 枚举值,只能取其中一个值 |
flag | 设置多个值,支持"|"操作符,不能在attr上设置format为flag,直接在attr节点下面添加flag节点即可 |
在代码里面获取
- 首先在xml里面使用一下.
<com.jhzl.customview.MineLineLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/black"
android:layout_gravity="center">
这里有个细节需要注意:
**android:orientation=“vertical”**就是我们在前面配置的attr里面的enum.
- MineLineLayout获取orientation
public MineLineLayout(Context context, AttributeSet attrs) {
super(context, attrs);
//获取MineLineLayout所有attr里面的内容
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.MineLineLayout);
//获取orientation
int index = a.getInt(R.styleable.MineLineLayout_android_orientation, -1);
if (index >= 0) {
setOrientation(index);
}
//回收TypedArray
a.recycle();
Log.d(TAG,"orientation = "+index);
}
打印结果: