Android下LineLayout實現View自動換行

        在進行Android開發的時候,比如我們添加view到LineLayout中,如果是水平佈局可能會一直水平添加導致產生“超出屏幕”的類似現象,所以就需要進行換行操作,下面是進行換行的代碼,可以直接使用~

         

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;

public class CustomLayout extends ViewGroup {
    private static final String TAG = "CustomLayout";

  public CustomLayout(Context context) {
      super(context);
  }

  public CustomLayout(Context context, AttributeSet attrs) {
      this(context, attrs, 0);
  }

  public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
  }

  /**
   * 要求所有的孩子測量自己的大小,然後根據這些孩子的大小完成自己的尺寸測量
   */
  @SuppressLint("NewApi") @Override
  protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
      // 計算出所有的childView的寬和高 
      measureChildren(widthMeasureSpec, heightMeasureSpec); 
      //測量並保存layout的寬高(使用getDefaultSize時,wrap_content和match_perent都是填充屏幕)
      //稍後會重新寫這個方法,能達到wrap_content的效果
      setMeasuredDimension( getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
              getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
  }

  /**
   * 爲所有的子控件擺放位置.
   */
  @Override
  protected void onLayout( boolean changed, int left, int top, int right, int bottom) {
      final int count = getChildCount();
      int childMeasureWidth = 0;
      int childMeasureHeight = 0;
      int layoutWidth = 0;    // 容器已經佔據的寬度
      int layoutHeight = 0;   // 容器已經佔據的寬度
      int maxChildHeight = 0; //一行中子控件最高的高度,用於決定下一行高度應該在目前基礎上累加多少
      for(int i = 0; i<count; i++){
          View child = getChildAt(i);
           //注意此處不能使用getWidth和getHeight,這兩個方法必須在onLayout執行完,才能正確獲取寬高
          childMeasureWidth = child.getMeasuredWidth(); 
          childMeasureHeight = child.getMeasuredHeight(); 
          if(layoutWidth<getWidth()){
                 //如果一行沒有排滿,繼續往右排列
                left = layoutWidth;
                right = left+childMeasureWidth;
                top = layoutHeight;
                bottom = top+childMeasureHeight;
          } else{
                 //排滿後換行
                layoutWidth = 0;
                layoutHeight += maxChildHeight;
                maxChildHeight = 0;

                left = layoutWidth;
                right = left+childMeasureWidth;
                top = layoutHeight;
                bottom = top+childMeasureHeight;
          }

          layoutWidth += childMeasureWidth;  //寬度累加
           if(childMeasureHeight>maxChildHeight){
                maxChildHeight = childMeasureHeight;
          }

           //確定子控件的位置,四個參數分別代表(左上右下)點的座標值
          child.layout(left, top, right, bottom);
      }
  }
}

 

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