當窗口在屏幕上方上,似乎顯示了大體正確的效果,但是起始位置距離窗口頂部的位置很怪,有一點空白。因工作緊張,沒思考,直接強行挪動來使用。但是當窗口在屏幕下部時,各個子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
截圖: