說來慚愧,我跟着視屏敲了一遍代碼,受益匪淺,本想跟大家分享,奈何道行太淺,這裏就不獻醜解說了(偶也說不清楚),姑且做一個實用主義者吧,有需要的朋友直接複製代碼就可以上手了。如果你是一隻好奇的貓,建議到慕課網中傾聽鴻洋大神的教誨,地址:http://www.imooc.com/video/5145
直奔主題:奉上流式標籤佈局FlowLayout大餐。
/**
* Created by JACK on 16/12/12.
*/
public class FlowLayout extends ViewGroup {
private Context mContext;
/**
* 適用於當New出一個對象的時候會調用一個參數的構造方法
*
* @param context
*/
public FlowLayout(Context context) {
this(context, null);
}
/**
* 在佈局文件中調用屬性但是沒有調用自定義屬性時會調用兩個參數的構造方法
*
* @param context
* @param attrs
*/
public FlowLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* 在佈局文件中當使用自定義屬性的時候會調用三個參數的構造方法
*
* @param context
* @param attrs
* @param defStyleAttr
*/
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 測量模式和測量值在其中
*
* @param widthMeasureSpec 父類穿來的寬度的測量值
* @param heightMeasureSpec 父類穿來的高度的測量值
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//------------傳入的精確值match_parent
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
// Log.e("TAG0","sizeWidth="+sizeWidth);
// Log.e("TAG0","sizeHeight="+sizeHeight);
//-------------------wrap_content
int width = 0;
int height = 0;
//記錄每一行的寬度和高度
int lineWidth = 0;
int lineHeight = 0;
//得到內部元素的個數
int cCount = getChildCount();
for (int i = 0; i < cCount; i++) {
View child = getChildAt(i);
//測量子View的寬和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
//得到LayoutParams(子View的LayoutParams其實是父佈局的LayouParams)
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
//子View的寬度和高度
int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
//換行
if (lineWidth + childWidth > sizeWidth-getPaddingLeft()-getPaddingRight()) {
//當前行的寬度和已經記錄的最大行的寬度進行對比留下最大寬度
//佈局的寬度width是最寬行的寬度
width = Math.max(width, lineWidth);
//重置行寬
lineWidth = childWidth;
//累加行高
height += lineHeight;
lineHeight = childHeight;
//不換行
} else {
//疊加行寬
lineWidth += childWidth;
//以最寬的子View的高度爲當前的行高
lineHeight = Math.max(lineHeight, childHeight);
}
//最後一個控件特殊處理(最後一行的高度沒有累加,寬度沒有比較)
//如果換行執行if就沒有處理換行後的佈局的寬度和高度
//如果不換行執行else就沒有疊加當前行的高度和比較最大的行寬
if (i == cCount -1) {
width = Math.max(width, lineWidth);
height += lineHeight;
}
}
/*if (modeWidth==MeasureSpec.AT_MOST){
setMeasuredDimension(width,height);
}else {
setMeasuredDimension(sizeWidth,sizeHeight);
}
if (modeHeight==MeasureSpec.AT_MOST){
setMeasuredDimension(width,height);
}else {
setMeasuredDimension(sizeWidth,sizeHeight);
}*///換做下面的代碼
setMeasuredDimension(
modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width+getPaddingLeft()+getPaddingRight(),
modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height+getPaddingTop()+getPaddingBottom()
);
//Log.e("TAG", "sizeWidth=" + sizeWidth);
//Log.e("TAG", "sizeHeight=" + sizeHeight);
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* 與當前ViewGroup對應的layoutparams
*
* @param attributeSet
* @return
*/
@Override
public LayoutParams generateLayoutParams(AttributeSet attributeSet) {
return new MarginLayoutParams(getContext(), attributeSet);//這裏只關注MarginLayoutParams
}
// @Override爲什麼上面的方法不提示?只有下面的方法可選擇
// protected LayoutParams generateLayoutParams(LayoutParams p) {
// return super.generateLayoutParams(p);
// }
/**
* 以行來存儲所有的View
*/
private List<List<View>> mAllViews = new ArrayList<>();
/**
* 每行的高度
*/
private List<Integer> mLineHeight = new ArrayList<>();
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//會多次調用onLayout,所以先clear
mAllViews.clear();
mLineHeight.clear();
//當前ViewGroup的寬度
int width = getWidth();//此時已經執行了onMeasure(),可以直接調用getWidth獲得寬度
int lineWidth = 0;
int lineHeight = 0;
List<View> lineViews = new ArrayList<>();
int cCount = getChildCount();
for (int i = 0; i < cCount; i++) {
View child = getChildAt(i);
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width-getPaddingRight()-getPaddingLeft()) {
mLineHeight.add(lineHeight);
//記錄當前行的Views
mAllViews.add(lineViews);
//重置寬和高
lineWidth = 0;
lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
//重置行View集合
lineViews = new ArrayList<>();
}
lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
lineViews.add(child);//別丟了
}//for end
//處理最後一行
mLineHeight.add(lineHeight);
mAllViews.add(lineViews);
//設置子View的位置
int left = getPaddingLeft();
int top = getPaddingTop();
//行數
int lineNum = mAllViews.size();
for (int i = 0; i < lineNum; i++) {
//當前行的所有View
lineViews = mAllViews.get(i);
lineHeight = mLineHeight.get(i);
for (int j = 0; j < lineViews.size(); j++) {
View child = lineViews.get(j);
if (child.getVisibility() == View.GONE) {
continue;
}
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int lc = left + lp.leftMargin;
int tc = top + lp.topMargin;
int rc = lc + child.getMeasuredWidth();
int bc = tc + child.getMeasuredHeight();
//對子View 進行佈局
child.layout(lc, tc, rc, bc);
left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
}
//換行
left = getPaddingLeft();
top += lineHeight;
}
}
}
下面是FlowLayout在佈局文件中的定義,可以直接作爲根佈局,也可以嵌套在其他佈局之中。
<?xml version="1.0" encoding="utf-8"?>
<com.jack.tagapp.FlowLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_flow_layout"
android:layout_width="match_parent"
android:background="#68e707"
android:padding="10dp"
android:layout_height="wrap_content"
>
</com.jack.tagapp.FlowLayout>
然後來看看怎麼用,使用Button相對簡單,但是使用TextView要自己寫佈局文件,不要直接new,我已經嘗試結果直接就三行沒有間隙的字母
public class MainActivity extends AppCompatActivity {
private String[] mVals=new String[]{
"Hello","Android","WelocmeToChina","Button","TopMarginLeft","Layout","AppCompatActivity","SaveInstanceState",
"HelloWorld","Android","Welocme","Button","Top","LayoutParams","AppCompatActivity","SaveInstanceState"
};
private FlowLayout mFlowLayout;
private LayoutInflater mInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFlowLayout= (FlowLayout) findViewById(R.id.main_flow_layout);
mInflater=LayoutInflater.from(this);
initData();
}
public void initData(){
for (int i = 0; i <mVals.length ; i++) {
// Button btn=new Button(this);
// ViewGroup.MarginLayoutParams lp=new ViewGroup.MarginLayoutParams(
// ViewGroup.MarginLayoutParams.WRAP_CONTENT,
// ViewGroup.MarginLayoutParams.WRAP_CONTENT
// );
// btn.setText(mVals[i]);
// btn.setClickable(false);
// //btn.setBackgroundColor(Color.BLUE);
// mFlowLayout.addView(btn,lp);//添加lp
TextView tv= (TextView) mInflater.inflate(R.layout.textview,mFlowLayout,false);
tv.setText(mVals[i]);
mFlowLayout.addView(tv);
}
}
}
最後奉上TextView的佈局和背景。
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HelloWorld"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textColor="#ffffff"
android:background="@drawable/textview_bg">
</TextView>
下面的TextView的背景定義在drawable下,起到了很好的美化作用,圓角背景補白等可以實現很漂亮的整體效果。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#f4c50b"/>
<corners android:radius="30dp"/>
<padding
android:top="8dp"
android:bottom="8dp"
android:left="10dp"
android:right="10dp"/>
</shape>
最後附上效果圖
最後向鴻洋大神標示敬意,任然希望大家還是抽點時間去看看視頻:http://www.imooc.com/video/5145