Android 流式布局FlowLayout 實現關鍵字標簽

1.介紹

流式布局的應用還是很廣泛的,比如搜索熱詞、關鍵詞標簽等,GitHub上已經有很多這樣的布局了,但是還是想著自己實現一下,最近一直在學自定義控件,也鞏固一下所學的知識。
本文實現的效果如下圖所示:

FlowLayout

2.思路

  • 繼承自RelativeLayout,可以直接使用RelativeLayout中的相關屬性,本文也可以修改為繼承ViewGroup,并不會有什么影響。
  • 在onMeasure方法中計算出所有childView的寬和高,然后根據childView的寬和高計算出布局自身的寬和高。
  • 在onLayout方法中計算出所有childView的位置并進行布局。
  • 封裝Line對象,管理每行上的View對象

3.實現

初始化一些屬性

public class FlowLayout extends RelativeLayout {

    // 水平間距,單位為dp
    private int horizontalSpacing = dp2px(10);
    // 豎直間距,單位為dp
    private int verticalSpacing = dp2px(10);
    // 行的集合
    private List<Line> lines = new ArrayList<Line>();
    // 當前的行
    private Line line;
    // 當前行使用的空間
    private int lineSize = 0;
    // 關鍵字大小,單位為sp
    private int textSize = sp2px(15);
    // 關鍵字顏色
    private int textColor = Color.BLACK;
    // 關鍵字背景框
    private int backgroundResource = R.drawable.bg_frame;
    // 關鍵字水平padding,單位為dp
    private int textPaddingH = dp2px(7);
    // 關鍵字豎直padding,單位為dp
    private int textPaddingV = dp2px(4);

    public FlowLayout(Context context) {
        this(context, null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.FlowLayoutAttrs, defStyleAttr, 0);

        int count = typedArray.getIndexCount();
        for (int i = 0; i < count; i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.FlowLayoutAttrs_horizontalSpacing:
                    horizontalSpacing = typedArray.getDimensionPixelSize(attr, dp2px(10));
                    break;

                case R.styleable.FlowLayoutAttrs_verticalSpacing:
                    verticalSpacing = typedArray.getDimensionPixelSize(attr, dp2px(10));
                    break;

                case R.styleable.FlowLayoutAttrs_textSize:
                    textSize = typedArray.getDimensionPixelSize(attr, sp2px(15));
                    break;

                case R.styleable.FlowLayoutAttrs_textColor:
                    textColor = typedArray.getColor(attr, Color.BLACK);
                    break;

                case R.styleable.FlowLayoutAttrs_backgroundResource:
                    backgroundResource = typedArray.getResourceId(attr, R.drawable.bg_frame);
                    break;

                case R.styleable.FlowLayoutAttrs_textPaddingH:
                    textPaddingV = typedArray.getDimensionPixelSize(attr, dp2px(7));
                    break;

                case R.styleable.FlowLayoutAttrs_textPaddingV:
                    verticalSpacing = typedArray.getDimensionPixelSize(attr, dp2px(4));
                    break;
            }
        }
        typedArray.recycle();
    }
    
    ...
}

onMeasure

首先獲取父容器傳入的寬高值與測量模式,計算出實際使用的寬和高,遍歷所有的childView,對childView進行測量,根據當前行已用的寬度判斷是否需要換行,然后累計所有高度,設置布局自身尺寸。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    // 實際可以用的寬和高
    int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
    int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingBottom() - getPaddingTop();
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);

    // Line初始化
    restoreLine();

    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        // 測量所有的childView
        int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
                widthMode == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : widthMode);
        int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
                heightMode == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : heightMode);
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

        if (line == null) {
            // 創建新一行
            line = new Line();
        }

        // 計算當前行已使用的寬度
        int measuredWidth = child.getMeasuredWidth();
        lineSize += measuredWidth;

        // 如果使用的寬度小于可用的寬度,這時候childView能夠添加到當前的行上
        if (lineSize <= width) {
            line.addChild(child);
            lineSize += horizontalSpacing;
        } else {
            // 換行
            newLine();
            line.addChild(child);
            lineSize += child.getMeasuredWidth();
            lineSize += horizontalSpacing;
        }
    }

    // 把最后一行記錄到集合中
    if (line != null && !lines.contains(line)) {
        lines.add(line);
    }

    int totalHeight = 0;
    // 把所有行的高度加上
    for (int i = 0; i < lines.size(); i++) {
        totalHeight += lines.get(i).getHeight();
    }
    // 加上行的豎直間距
    totalHeight += verticalSpacing * (lines.size() - 1);
    // 加上上下padding
    totalHeight += getPaddingBottom();
    totalHeight += getPaddingTop();

    // 設置自身尺寸
    // 設置布局的寬高,寬度直接采用父view傳遞過來的最大寬度,而不用考慮子view是否填滿寬度
    // 因為該布局的特性就是填滿一行后,再換行
    // 高度根據設置的模式來決定采用所有子View的高度之和還是采用父view傳遞過來的高度
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
            resolveSize(totalHeight, heightMeasureSpec));
}

附上restoreLine與newLine方法

private void restoreLine() {
    lines.clear();
    line = new Line();
    lineSize = 0;
}

private void newLine() {
    // 把之前的行記錄下來
    if (line != null) {
        lines.add(line);
    }
    // 創建新的一行
    line = new Line();
    lineSize = 0;
}

Line

封裝了每行上的View對象,提供添加與繪制childView的方法。

/**
 * 管理每行上的View對象
 */
class Line {
    // 子控件集合
    private List<View> children = new ArrayList<View>();
    // 行高
    int height;

    /**
     * 添加childView
     *
     * @param childView 子控件
     */
    public void addChild(View childView) {
        children.add(childView);

        // 讓當前的行高是最高的一個childView的高度
        if (height < childView.getMeasuredHeight()) {
            height = childView.getMeasuredHeight();
        }
    }

    /**
     * 設置childView的繪制區域
     *
     * @param left 左上角x軸坐標
     * @param top  左上角y軸坐標
     */
    public void layout(int left, int top) {
        int totalWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        // 當前childView的左上角x軸坐標
        int currentLeft = left;

        for (int i = 0; i < children.size(); i++) {
            View view = children.get(i);
            // 設置childView的繪制區域
            view.layout(currentLeft, top, currentLeft + view.getMeasuredWidth(),
                    top + view.getMeasuredHeight());
            // 計算下一個childView的位置
            currentLeft = currentLeft + view.getMeasuredWidth() + horizontalSpacing;
        }
    }

    public int getHeight() {
        return height;
    }

    public int getChildCount() {
        return children.size();
    }
}

onLayout

指定所有childView的位置,調用Line對象中的layout方法。

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    int left = getPaddingLeft();
    int top = getPaddingTop();
    for (int i = 0; i < lines.size(); i++) {
        Line line = lines.get(i);
        line.layout(left, top);
        // 計算下一行的起點y軸坐標
        top = top + line.getHeight() + verticalSpacing;
    }
}

setFlowLayout

用于設置FlowLayout中的內容,并提供點擊事件處理。

public void setFlowLayout(List<String> list, final OnItemClickListener onItemClickListener) {
    for (int i = 0; i < list.size(); i++) {
        final TextView tv = new TextView(getContext());

        // 設置TextView屬性
        tv.setText(list.get(i));
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        tv.setTextColor(textColor);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(textPaddingH, textPaddingV, textPaddingH, textPaddingV);

        tv.setClickable(true);
        tv.setBackgroundResource(backgroundResource);
        this.addView(tv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemClickListener.onItemClick(tv.getText().toString());
            }
        });
    }
}

public interface OnItemClickListener {
    void onItemClick(String content);
}

使用方法

  • 在項目根目錄的build.gradle文件中加入如下代碼
maven { url "https://jitpack.io" }
jitpack
  • 在app根目錄的buil.gradle文件中加入依賴
compile 'com.github.alidili:FlowLayout:v1.0'
加入依賴
  • 在Activity中使用,設置點擊事件

相關屬性(字體大小、顏色、間距等)可以在布局文件中設置,也可以通過set方法設置。

public class MainActivity extends AppCompatActivity {

    private FlowLayout flKeyword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        flKeyword = (FlowLayout) findViewById(R.id.fl_keyword);

        List<String> list = new ArrayList<>();
        list.add("關鍵詞一");
        list.add("關鍵詞二");
        list.add("關鍵詞三");
        list.add("關鍵詞四");
        list.add("關鍵詞五");
        flKeyword.setFlowLayout(list, new FlowLayout.OnItemClickListener() {
            @Override
            public void onItemClick(String content) {
                Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
  • 布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.yang.flowlayoutlibrary.FlowLayout
        android:id="@+id/fl_keyword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        app:itemColor="@color/colorAccent"
        app:itemSize="15sp" />

</RelativeLayout>

4.寫在最后

源碼已托管到GitHub上,歡迎Fork,覺得還不錯就Start一下吧!

點擊下載源碼

GitHub地址:https://github.com/alidili/FlowLayout

歡迎同學們吐槽評論,如果你覺得本篇博客對你有用,那么就留個言或者點下喜歡吧(^-^)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內容