1.定義ShowButtonLayout extends ViewGroup,重寫onMeasure方法
/** * 測量寬度和高度 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //獲取流式佈局的寬度和模式 int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); //獲取流式佈局的高度和模式 int heightSize = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//使用wrap_content的流式佈局的最終寬度和高度
int width = 0, height = 0;
//記錄每一行的寬度和高度
int lineWidth = 0, lineHeight = 0;
//得到內部元素的個數
int count = getChildCount();
mChildPos.clear();
for (int i = 0; i < count; i++) {
//獲取對應索引的view
View child = getChildAt(i);
//測量子view的寬和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
//子view佔據的寬度
int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
//子view佔據的高度
int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
//換行
if (lineWidth + childWidth > widthSize - getPaddingLeft() - getPaddingRight()) {
//取最大的行寬為流式佈局寬度
width = Math.max(width, lineWidth);
//疊加行高得到流式佈局高度
height += lineHeight;
//重置行寬度為第一個View的寬度
lineWidth = childWidth;
//重置行高度為第一個View的高度
lineHeight = childHeight;
//記錄位置
mChildPos.add(new ChildPos(
getPaddingLeft() + lp.leftMargin,
getPaddingTop() + height + lp.topMargin,
getPaddingLeft() + childWidth - lp.rightMargin,
getPaddingTop() + height + childHeight - lp.bottomMargin));
} else { //不換行
//記錄位置
mChildPos.add(new ChildPos(
getPaddingLeft() + lineWidth + lp.leftMargin,
getPaddingTop() + height + lp.topMargin,
getPaddingLeft() + lineWidth + childWidth - lp.rightMargin,
getPaddingTop() + height + childHeight - lp.bottomMargin));
//疊加子View寬度得到新行寬度
lineWidth += childWidth;
//取當前行子View最大高度作為行高度
lineHeight = Math.max(lineHeight, childHeight);
}
//最後一個控制元件
if (i == count - 1)
{
width = Math.max(lineWidth, width);
height += lineHeight;
}
}
setMeasuredDimension(
widthMode == MeasureSpec.EXACTLY ? widthSize : width + getPaddingLeft() + getPaddingRight(),
heightMode == MeasureSpec.EXACTLY ? heightSize : height + getPaddingTop() + getPaddingBottom());
}
複製程式碼
2.在xml檔案中引用
<com.xsy.lib.ShowButtonLayout
android:id="@+id/mShowBtnLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
複製程式碼
3.設定資料
for (int i = 0; i < hotWords.length; i++) { TextView view = (TextView) LayoutInflater.from(this).inflate(R.layout.hot_search_tv, mShowBtnLayout, false); view.setText(hotWords[i]); view.setTag(hotWords[i]); view.setOnClickListener(new View.OnClickListener() {//設定點選事件 @Override public void onClick(View view) { String keyword = (String) view.getTag(); Toast.makeText(MainActivity.this,keyword,Toast.LENGTH_LONG).show(); } }); mShowBtnLayout.addView(view);//新增到該view中 }