需求
大家先稍微思考一下这个布局怎么实现。
我想很多人想到的步骤应该是:
1. 用RelativeLayout或者FrameLayout作为父布局。
2. 先放置编辑框,再放置红色的文字框
3. 红色框高度是不固定,设置数据后,计算红色框的高度,再设置好下面输入框的marginTop
好像也不难,但是每次遇到这样的需求就得计算,感觉有点麻烦,我在想有没有更简单的方法?
我的想法是:
1. 用LinearLayout作为父布局,方向Vertical。
2. 先放置红色的文字框,后放置编辑框
3. 编辑框设置-marginTop
但是这样做有一个问题,就是后放置的编辑框 会盖住上面的View,要是可以改变视图绘制层次,就好办了,接下来就是介绍如何实现改变ViewGroup的绘制层次
实现思路
1.获取View的布局层次
2.根据View的布局层次排序,改变View在ViewGroup中的绘制顺序
1. 获取view的布局层次
我们先解决第一个问题,如何为View加一个布局层次的属性。我们很容易想到在ViewGroup中,View 有属性gravity这样的属性。我们需要了解这样的属性是怎么加上去的,下面以Linearlayout的修改为例子,其他的ViewGroup可自行修改。
第一步:添加一个layer属性在res/values文件夹加上attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LayerParams">
<!-- 自定义的属性名称 和对应的单位 -->
<attr name="layer" format="integer"/>
</declare-styleable>
</resources>
第二步:继承已有的LayoutParams,加载属性
public class LayerLinLayoutParams extends LinearLayout.LayoutParams {
int layer = 0;
public LayerLinLayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.LayerParams);
//获取设置在子控件上的位置属性
layer = a.getInt(R.styleable.LayerParams_layer, 0);
a.recycle();
}
public LayerLinLayoutParams(int width, int height) {
super(width, height);
}
public LayerLinLayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
第三步:需要重写generateLayoutParams三个方法
public class