当窗口在屏幕上方上,似乎显示了大体正确的效果,但是起始位置距离窗口顶部的位置很怪,有一点空白。因工作紧张,没思考,直接强行挪动来使用。但是当窗口在屏幕下部时,各个子view完全不见了。很费解。
原始代码可能错误理解了这个方法的参数:
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom) {
}
这个方法的参数是本窗口相对于其父亲(比如屏幕)的位置参数,而不是相对屏幕的绝对位置参数。在这个方法里面我们要计算child view相对于本窗口的相对位置参数,而不是相对屏幕的绝对位置参数,并将这个参数设置到这个方法:
child.layout( int l, int t, int r, int b)
所以能正确换行的onLayout方法代码是:
@Override
protected void onLayout (boolean arg0, int arg1, int arg2, int arg3, int arg4) {
Log. d( "", "onLayout parants: changed = " + arg0 + " left = " + arg1
+ " top = " + arg2 + " right = " + arg3 + " botom = " + arg4);
int parants_width = arg3 - arg1;//ViewGroup宽度
final int count = getChildCount();
int rightMove = 0;
int bottomMove = 0;
for (int i = 0; i < count; i++) {
View child = this .getChildAt(i);
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
if (i == 0){
bottomMove = height + VIEW_MARGIN ;
}
rightMove += width + VIEW_MARGIN ;
if (rightMove > parants_width) {//换行
rightMove = width + VIEW_MARGIN ;
bottomMove += height + VIEW_MARGIN ;
} else {
}
child.layout(rightMove - width, bottomMove - height, rightMove, bottomMove);
Log. d( "", "onLayout params: " +(rightMove)+" "+(bottomMove) + " "+ width+ " " +height);
Log. d( "", "onLayout child: " +(rightMove - width)+" "+(bottomMove - height) + " "+ rightMove+ " " +bottomMove);
}
}
完整代码:https://github.com/maxyou/AutoWrapViewGroup
截图: