---
title: "LinearLayout 自动换行 "
author: "xixinfei"
date: "2014-08-22T16:05:37Z"
tags: []
categories: ["移动开发"]
slug: "linearlayout"
draft: false
lastmod: "2014-08-22T16:05:37Z"
id: 2107906
url: "https://xixinfei.iteye.com/blog/2107906"
---

由于前段时间项目中使用 到了自动换行的线性布局,本来打算用表格布局在里面一个个的用Java代码添加ImageView的，但是添加的View控件是不确定的，因为得靠服务器 的数据返回，就这样手动用Java代码画布局的方式就这样夭折了，因为在表哥布局中我无法确定一行显示多少个ImageView的数目，所以无法动态添 加，最后自能自己去看看那种能够换行的线性布局了，线性布局比较不好的是不能自动换行，也就是当设置LinearLayout的orentation 设置为vertical 为竖直方向也就是只有一列，每行只能显示一个View或者View的子类，当设置LinearLayout的orentitation为 Horizontal，LinearLayout的只能显示为一行，横向显示，当屏幕满了的时候，View控件并不会自动换行，所以我们要做的就是在 LinearLayout满的时候自动换行。

需 要了解的是怎么样绘制根据子控件的长宽绘制父控件的宽度与高度，所以需要传入的参数控件的高度,视图分为两种一种是View类型的，代表控件有 TextView,Button,EditText 等等，还有一种是装视图的容器控件继承自ViewGroup的控件，如LinearLayout,RelativeLayout，TabHost等等控 件，需要自动换行的线性布局的话，就需要根据子控件的高度与宽度，来动态加载父控件的高度与宽度,所以需要在构造函数中传入每一个子控件的固定的高度，或 者是动态设置子控件的高度与宽度。

将 自定义的LinearLayout 也继承自ViewGroup 并且重写抽象类ViewGrouop的几个方法:onMeasure(),onLayout(),dispathDraw()  三个方法的意思分别是:第一个onMeasure()是用来计算控件以及子控件所占用的区域,第二个onLayout()是控制子控件的换行,第三个可 写可不写，主要是用来绘制控件的边框，

自定义LinearLayout的代码如下:

 

**\[java]** [view plain](http://blog.csdn.net/long704480904/article/details/9011115 "view plain")[copy](http://blog.csdn.net/long704480904/article/details/9011115 "copy")[print](http://blog.csdn.net/long704480904/article/details/9011115 "print")[?](http://blog.csdn.net/long704480904/article/details/9011115 "?")

001. package com.huanglong.mylinearlayout;
002. import android.content.Context;
003. import android.graphics.Canvas;
004. import android.graphics.Color;
005. import android.graphics.Paint;
006. import android.graphics.Rect;
007. import android.util.AttributeSet;
008. import android.view.View;
009. import android.view.ViewGroup;
010. /\**
011. * @author huanglong 2013-5-28 自定义自动换行LinearLayout
012. \*/
013. public class FixGridLayout extends ViewGroup {
014. private int mCellWidth;
015. private int mCellHeight;
016. public FixGridLayout(Context context) {
017. super(context);
018. }
019. public FixGridLayout(Context context, AttributeSet attrs) {
020. super(context, attrs);
021. }
022. public FixGridLayout(Context context, AttributeSet attrs, int defStyle) {
023. super(context, attrs, defStyle);
024. }
025. public void setmCellWidth(int w) {
026. mCellWidth = w;
027. requestLayout();
028. }
029. public void setmCellHeight(int h) {
030. mCellHeight = h;
031. requestLayout();
032. }
033. /\**
034. * 控制子控件的换行
035. \*/
036. @Override
037. protected void onLayout(boolean changed, int l, int t, int r, int b) {
038. int cellWidth = mCellWidth;
039. int cellHeight = mCellHeight;
040. int columns = (r - l) / cellWidth;
041. if (columns &lt; 0) {
042. columns = 1;
043. }
044. int x = 0;
045. int y = 0;
046. int i = 0;
047. int count = getChildCount();
048. for (int j = 0; j &lt; count; j++) {
049. final View childView = getChildAt(j);
050. // 获取子控件Child的宽高
051. int w = childView.getMeasuredWidth();
052. int h = childView.getMeasuredHeight();
053. // 计算子控件的顶点坐标
054. int left = x + ((cellWidth - w) / 2);
055. int top = y + ((cellHeight - h) / 2);
056. // int left = x;
057. // int top = y;
058. // 布局子控件
059. childView.layout(left, top, left + w, top + h);
060. if (i &gt;= (columns - 1)) {
061. i = 0;
062. x = 0;
063. y += cellHeight;
064. } else {
065. i++;
066. x += cellWidth;
067. }
068. }
069. }
070. /\**
071. * 计算控件及子控件所占区域
072. \*/
073. @Override
074. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
075. // 创建测量参数
076. int cellWidthSpec = MeasureSpec.makeMeasureSpec(mCellWidth, MeasureSpec.AT\_MOST);
077. int cellHeightSpec = MeasureSpec.makeMeasureSpec(mCellHeight, MeasureSpec.AT\_MOST);
078. // 记录ViewGroup中Child的总个数
079. int count = getChildCount();
080. // 设置子空间Child的宽高
081. for (int i = 0; i &lt; count; i++) {
082. View childView = getChildAt(i);
083. /*
084. * 090 This is called to find out how big a view should be. 091 The
085. * parent supplies constraint information in the width and height
086. * parameters. 092 The actual mesurement work of a view is performed
087. * in onMeasure(int, int), 093 called by this method. 094 Therefore,
088. * only onMeasure(int, int) can and must be overriden by subclasses.
089. * 095
090. \*/
091. childView.measure(cellWidthSpec, cellHeightSpec);
092. }
093. // 设置容器控件所占区域大小
094. // 注意setMeasuredDimension和resolveSize的用法
095. setMeasuredDimension(resolveSize(mCellWidth * count, widthMeasureSpec),
096. resolveSize(mCellHeight * count, heightMeasureSpec));
097. // setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
098. // 不需要调用父类的方法
099. // super.onMeasure(widthMeasureSpec, heightMeasureSpec);
100. }
101. /\**
102. * 为控件添加边框
103. \*/
104. @Override
105. protected void dispatchDraw(Canvas canvas) {
106. // 获取布局控件宽高
107. int width = getWidth();
108. int height = getHeight();
109. // 创建画笔
110. Paint mPaint = new Paint();
111. // 设置画笔的各个属性
112. mPaint.setColor(Color.BLUE);
113. mPaint.setStyle(Paint.Style.STROKE);
114. mPaint.setStrokeWidth(10);
115. mPaint.setAntiAlias(true);
116. // 创建矩形框
117. Rect mRect = new Rect(0, 0, width, height);
118. // 绘制边框
119. canvas.drawRect(mRect, mPaint);
120. // 最后必须调用父类的方法
121. super.dispatchDraw(canvas);
122. }
123. }

然后在Xml文件中引用自己定义的控件,在Java代码中调用:

 

**\[java]** [view plain](http://blog.csdn.net/long704480904/article/details/9011115 "view plain")[copy](http://blog.csdn.net/long704480904/article/details/9011115 "copy")[print](http://blog.csdn.net/long704480904/article/details/9011115 "print")[?](http://blog.csdn.net/long704480904/article/details/9011115 "?")

01. package com.huanglong.mylinearlayout;
02. import android.os.Bundle;
03. import android.app.Activity;
04. import android.view.Menu;
05. import android.view.MenuItem;
06. import android.widget.CheckBox;
07. import android.widget.SimpleAdapter;
08. import android.support.v4.app.NavUtils;
09. public class MainActivity extends Activity {
10. private SimpleAdapter adapter;
11. @Override
12. public void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity\_main);
15. FixGridLayout fixGridLayout = (FixGridLayout) findViewById(R.id.ll);
16. fixGridLayout.setmCellHeight(30);
17. fixGridLayout.setmCellWidth(100);
18. for (int i = 0; i &lt; 7; i++) {
19. CheckBox box = new CheckBox(MainActivity.this);
20. box.setText("第"+i+"个");
21. fixGridLayout.addView(box);
22. }
23. }
24. @Override
25. public boolean onCreateOptionsMenu(Menu menu) {
26. getMenuInflater().inflate(R.menu.activity\_main, menu);
27. return true;
28. }
29. }

 

效果截图:

![](http://img.blog.csdn.net/20130603154210968)