Android源碼分享-自動換行LinearLayout

Android開發中,不少人會遇到滿行就自動換到下一行的界面需求,而Android自帶的LinearLayout佈局自能橫排或者豎排,不夠顯示就加ScrollView,橫豎混排就不行了。這裏給你們分享一個能夠實現自動換行的LinearLayout。java

import java.util.Hashtable;android

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;ide

/**
* 自動換行的LinearLayout
* @author idengpan
*
*/
@SuppressWarnings({ 「unchecked」,」rawtypes」 })
public class AutoNextLineLinearlayout extends LinearLayout {
int mLeft, mRight, mTop, mBottom;
Hashtable map = new Hashtable();佈局

public AutoNextLineLinearlayout(Context context) {
super(context);
}spa

public AutoNextLineLinearlayout(Context context, int horizontalSpacing, int verticalSpacing) {
super(context);
}.net

public AutoNextLineLinearlayout(Context context, AttributeSet attrs) {
super(context, attrs);
}orm

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {ci

int mWidth = MeasureSpec.getSize(widthMeasureSpec);
int mCount = getChildCount();
int mX = 0;
int mY = 0;
mLeft = 0;
mRight = 0;
mTop = 5;
mBottom = 0;開發

int j = 0;get

View lastview = null;
for (int i = 0; i < mCount; i++) {
final View child = getChildAt(i);

child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
// 此處增長onlayout中的換行判斷,用於計算所需的高度
int childw = child.getMeasuredWidth();
int childh = child.getMeasuredHeight();
mX += childw; // 將每次子控件寬度進行統計疊加,若是大於設定的高度則須要換行,高度即Top座標也需從新設置

Position position = new Position();
mLeft = getPosition(i – j, i);
mRight = mLeft + child.getMeasuredWidth();
if (mX >= mWidth) {
mX = childw;
mY += childh;
j = i;
mLeft = 0;
mRight = mLeft + child.getMeasuredWidth();
mTop = mY + 5;
// PS:若是發現高度仍是有問題就得本身再細調了
}
mBottom = mTop + child.getMeasuredHeight();
mY = mTop; // 每次的高度必須記錄 不然控件會疊加到一塊兒
position.left = mLeft;
position.top = mTop + 3;
position.right = mRight;
position.bottom = mBottom;
map.put(child, position);
}
setMeasuredDimension(mWidth, mBottom);
}

@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(0, 0); // default of 1px spacing
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
Position pos = (Position) map.get(child);
if (pos != null) {
child.layout(pos.left, pos.top, pos.right, pos.bottom);
} else {
Log.i(「MyLayout」, 「error」);
}
}
}

private class Position {
int left, top, right, bottom;
}

public int getPosition(int IndexInRow, int childIndex) {
if (IndexInRow > 0) {
return getPosition(IndexInRow – 1, childIndex – 1) + getChildAt(childIndex – 1).getMeasuredWidth() + 8;
}
return getPaddingLeft();
}
}

用法和普通的LinearLayout相似,在XML佈局文件中寫入這個自定義類的完整路徑,將android:orientation屬性指定爲horizontal(默認)便可。

相關文章
相關標籤/搜索