我想了几种解决方法:
1、将removeAllViews()移除所有子view,然后再按需要的顺序add进去
2、安卓自带了bringTofrount()可以将一个子View移动到最前,
其中的bringTofrount()只能把子view移动到最前面,不能任意改变view的前后关系,
可以不同子view多次调用这个方法
3、安卓5.0之后的view有一个z轴属性,可以关注一下,
4、设置两套view其中一套是镜像,也就是只用来显示的,根据要求进行setVisibility(INVISIBLE)或者setVisibility(VISIBLE);
着重看一下bringTofrount()这种方式
其实bringTofrount()方法是调用了ViewGroup中的
bringChildToFront(),继续向父类追踪会发现其实现原理
public void bringChildToFront(View child) { final int index = indexOfChild(child); if (index >= 0) { removeFromArray(index); addInArray(child, mChildrenCount); child.mParent = this; requestLayout(); invalidate(); } }注意到removeFromArray(index);的实现如下
private void removeFromArray(int index) { final View[] children = mChildren; if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) { children[index].mParent = null; } final int count = mChildrenCount; if (index == count - 1) { children[--mChildrenCount] = null; } else if (index >= 0 && index < count) { System.arraycopy(children, index + 1, children, index, count - index - 1); children[--mChildrenCount] = null; } else { throw new IndexOutOfBoundsException(); } if (mLastTouchDownIndex == index) { mLastTouchDownTime = 0; mLastTouchDownIndex = -1; } else if (mLastTouchDownIndex > index) { mLastTouchDownIndex--; } }其中这句final View[] children = mChildren;引用了mChildren这个成员变量,
而该成员变量在ViewGroup中的申明是私有的,也就是说无法通过子类来进行操作private View[] mChildren;曾经看过有人通过反射机制调用安卓内部Hidden的函数,待闲余时间再试另外更改view的前后关系对于像帧布局或者相对布局一般不会打乱布局的横向关系,但是对于线性布局则会完全打乱这种结构,这个必须要注意