不等寬子view自動換行的窗口(auto wrap viewgroup)

需要一個窗口來顯示一堆不等長的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
截圖:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章