1. 程式人生 > >流式佈局 FlowLayout 的簡單使用

流式佈局 FlowLayout 的簡單使用

先給大家看效果圖:


歷史記錄本地儲存到share裡面,在onStart裡面獲取呼叫資料,點選搜尋的時候新增進share。

匯入依賴:

compile 'com.nex3z:flow-layout:1.2.2'
https://github.com/nex3z/FlowLayout

Usage:

<com.nex3z.flowlayout.FlowLayout
android:id="@+id/flow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flChildSpacing="7dp"
app:flRowSpacing=
"8dp" />

屬性說明

這是github上的屬性介紹,看不懂的可以略過,我後面有中文翻譯,以及效果展示。

AttributeFormatDescription
flFlowbooleantrue to allow flow. false to restrict all child views in one row. The default is true.
flChildSpacingauto/dimensionThe horizontal spacing between child views. Either auto, or a fixed size. The default is 0dp.
flChildSpacingForLastRowauto/align/
dimension
The horizontal spacing between child views of the last row. Either autoalign or a fixed size. If not set, childSpacing will be used instead.
flRowSpacingauto/dimensionThe vertical spacing between rows. Either auto, or a fixed size. The default is 0dp.
flRtlbooleantrue to layout child views from right to left. false
 to layout from left to right. The default isfalse.
flMaxRowsintegerThe maximum height of FlowLayout in terms of number of rows.

中文:

FlowLayout flowLayout = (FlowLayout) findViewById(R.id.flow);
for (int i = 0; i < strList.size(); i++) {
    TextView textView = buildLabel(strList.get(i));
    flowLayout.addView(textView);
}
flowlayout就是一個佈局,像這樣新增textView進去,就初始化好了。

屬性:

//預設為true,flase只顯示一行

flowLayout.setFlow(false);
如圖所示: 


//這個三個屬性都是間距,橫縱的距離

flowLayout.setChildSpacing(8);
flowLayout.setRowSpacing(8);
flowLayout.setChildSpacingForLastRow(8);

//這個屬性預設是false,為true排列方向從右到左,上效果圖。

app:flRtl="true"
這個屬性我沒有在程式碼裡找到,只能在xml裡面設定
//最大行數,如果設定為2那麼顯示出的行數只有兩行。

flowLayout.setMaxRows(2);

如之前的圖片,我本來有四行,設定以後只顯示兩行。 

我使用這個佈局用到的程式碼如下:

for (int i = 0; i < strList.size(); i++) {
    TextView textView = buildLabel(strList.get(i));
    flowLayout.addView(textView);
}

private TextView buildLabel(final String text) {
    TextView textView = new TextView(this);
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    textView.setPadding((int) dpToPx(16), (int) dpToPx(8), (int) dpToPx(16), (int) dpToPx(8));
    textView.setBackgroundResource(R.drawable.bg_gray);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
public void onClick(View v) {
            et.setText(text);
        }
    });
    return textView;
}

private float dpToPx(float dp) {
    return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}

簡單介紹這裡了。