两个view并列显示,第二个view跟在第一个view的后面,如果长度过长,则第一个view宽度缩小。
直接上代码 用就完了!
public class TextWithImageLayout extends LinearLayout {
private final int MARGIN = 40;
private int mMargin;
private int[] mChildWidthList;
public TextWithImageLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mMargin = MARGIN;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int count = getChildCount();
View firstChild = getChildAt(0);
if (count > 1) {
int firstChildWidth = firstChild.getMeasuredWidth();
int firstChildHeight = firstChild.getMeasuredHeight();
int otherChildrenWidth = 0;
int otherChildrenHeight = 0;
for (int i = 1; i < count; i++) {
View child = getChildAt(i);
int width;
if (mChildWidthList == null) {
width = child.getMeasuredWidth();
} else {
width = mChildWidthList[i - 1];
}
otherChildrenWidth += width;
child.measure(width | MeasureSpec.EXACTLY, child.getMeasuredHeight() | MeasureSpec.EXACTLY);
otherChildrenHeight = child.getMeasuredHeight();
}
int margin = mMargin * (count - 1);
if (firstChildWidth + otherChildrenWidth + margin > widthSize) {
firstChildWidth = widthSize - otherChildrenWidth - margin;
}
heightSize = firstChildHeight > otherChildrenHeight ? firstChildHeight : otherChildrenHeight;
firstChild.measure(firstChildWidth | MeasureSpec.EXACTLY,
firstChildHeight | MeasureSpec.EXACTLY);
} else {
firstChild.measure(firstChild.getMeasuredWidth(), firstChild.getMeasuredHeight());
heightSize = firstChild.getMeasuredHeight();
}
setMeasuredDimension(widthSize, heightSize);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int count = getChildCount();
int left = 0;
for (int i = 0; i < count; i++) {
final View child = this.getChildAt(i);
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
int top = (b - t) / 2 - height / 2;
child.layout(left, top, left + width, top + height);
left = left + width + mMargin;
}
}
public int[] getChildWidthList() {
return mChildWidthList;
}
public void setChildWidthList(int[] childWidthList) {
this.mChildWidthList = childWidthList;
}
}