需要一个窗口来显示一堆不等长的TextView,这些子view横向顺序排列,超出窗口宽度则换行。
在“cn.bing.com”上使用关键字“自动换行viewgroup”进行搜索,发现最前面6~7个搜索结果都来自同一篇博客的转载:
没细看代码,直接拷贝用了。
当窗口在屏幕上方上,似乎显示了大体正确的效果,但是起始位置距离窗口顶部的位置很怪,有一点空白。因工作紧张,没思考,直接强行挪动来使用。但是当窗口在屏幕下部时,各个子view完全不见了。很费解。
无
奈只好细看了一下这段代码,并对比了FrameLayout的onLayout方法
。我的理解是,这段被多次转载的博文的代码可能有误。因我水平很有限,不敢肯定,以下说法全不负责。
原始代码可能错误理解了这个方法的参数:
@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
截图:
本文探讨了一个自定义视图组在不同窗口位置显示不等长TextView时的自动换行问题,通过分析代码逻辑并修正onLayout方法参数理解错误,实现了正确换行效果。提供了解决方案及完整代码,适用于Android开发。
757

被折叠的 条评论
为什么被折叠?



