自定義標(biāo)簽布局(流布局)

相信大家在做應(yīng)用的時(shí)候經(jīng)常會(huì)遇到顯示標(biāo)簽的情況,例如(“上班族,天枰座”這樣的),若干個(gè)標(biāo)簽長(zhǎng)短不一,每個(gè)標(biāo)簽之間還有一定的間隙,并且一行顯示不下之后,下一個(gè)標(biāo)簽顯示就需要換行,本篇文章就自定義一個(gè)View,來(lái)實(shí)現(xiàn)所說(shuō)的這個(gè)效果。

首先我們先來(lái)看看實(shí)現(xiàn)以后是什么樣的:

Paste_Image.png

通過這個(gè)實(shí)際的實(shí)現(xiàn)效果我們可以做出下面的分析:
1.每個(gè)item的寬度不同
2.行/列之間有間隔
3.數(shù)據(jù)和布局進(jìn)行分離,并且布局可以自定義,于是我們考慮利用android的adapter的特性進(jìn)行實(shí)現(xiàn)
4.有自動(dòng)換行的功能

這個(gè)View大概要實(shí)現(xiàn)上面的效果,下面就開始擼碼:
先建立好這個(gè)View,繼承自ViewGroup:

public class TagView extends ViewGroup {
}

為了讓其使用更加靈活,我們自定義幾個(gè)屬性:

<declare-styleable name="TagView">
        <attr name="maxLine" format="integer" />//最多允許多少行,超過的就不進(jìn)行顯示了
        <attr name="itemSpace" format="dimension" />//每個(gè)item之間的寬度(每行的高度,也可以多定義一個(gè)高度)
        <attr name="gravity" format="enum">////子View擺放時(shí)貼著父布局上邊還是下邊
            <enum name="top" value="1" />
            <enum name="bottom" value="2" />
        </attr>
    </declare-styleable>

定義好了以后,我們就可以在XML文件里畫布局了:

  <com.test.xiao.TagView
            android:id="@+id/gv_tag"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/iv_photo"
            android:layout_alignParentLeft="true"
            android:layout_below="@id/tv_content"
            android:layout_toLeftOf="@id/iv_photo"
            app:gravity="bottom"http://貼著下邊進(jìn)行擺放
            app:itemSpace="3dp"
            app:maxLine="2" />

item的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_main_tag_sub"http://橙色的背景
    android:ellipsize="end"
    android:gravity="center"
    android:maxLines="1"
    android:paddingBottom="1dp"
    android:paddingLeft="2dp"
    android:paddingRight="2dp"
    android:paddingTop="1dp"
    android:text="TextView01"
    android:textColor="@color/white"
    android:textSize="@dimen/ss_small_textSize" />

好了,這些準(zhǔn)備工作完成以后,我們就可以開始實(shí)現(xiàn)View的功能了,首先定義好相關(guān)變量并進(jìn)行初始化:

public class TagView extends ViewGroup {
private int itemSpace = 0;//item之間的間距
    private Adapter mAdapter;//獲取數(shù)據(jù)和子item的適配器,這個(gè)adapter就是android原生提供的adapter
    private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(項(xiàng)目中暫時(shí)未用到垂直需求,所以暫時(shí)不需要)
    private SparseArray<SparseArray<View>> views;//用于記錄第幾行,第幾個(gè)item
    private SparseArray<Integer> maxHeights;//記錄每行的最大高度
    private int maxLine;//設(shè)置最大的行數(shù)
    private int gravity;//子View貼著上邊還是下邊(默認(rèn)上邊),1是上邊,2是下邊
public TagView(Context context) {
        super(context);
        init(null);
    }

    public TagView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attributeSet) {
        views = new SparseArray<>();
        maxHeights = new SparseArray();
        if (attributeSet == null) {
            itemSpace = Utils.dp2px(getContext(), 5);
            maxLine = 10;// 默認(rèn)最大行數(shù)
        } else {
            TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
            itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
            gravity = array.getInt(R.styleable.TagView_gravity, 1);
            maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
            array.recycle();
        }
    }
}

接下來(lái)我們需要在onMeasure里通過adapter獲取到相關(guān)的view,并且測(cè)量出每個(gè)view的寬度和高度,根據(jù)寬度來(lái)計(jì)算出我們需要多少行,每行分別需要列來(lái)放這些item:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int needWidth = MeasureSpec.getSize(widthMeasureSpec);
        int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
        int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
        int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
        if (mAdapter != null && mAdapter.getCount() > 0) {//如果adapter沒有數(shù)據(jù),則不進(jìn)行繪制,直接調(diào)用super.onMeasure
            View child = null;//從adaper中獲取的子View
            int childWidth = 0;//子View的寬度
            int currentLineWidth = 0;//當(dāng)前行的總寬度
            int currentLine = 0;//當(dāng)前是第幾行
            int currentElement = 0;//當(dāng)前行的第幾個(gè)元素
            int maxHeight = 0;//當(dāng)前行的最大高度
            int resultHeihgt = 0;//通過子View的測(cè)量情況最終算出來(lái)的父View高度
            boolean isMaxLine = false;//當(dāng)前是否已經(jīng)到達(dá)最大行
            for (int i = 0; i < mAdapter.getCount(); i++) {//通過adapter來(lái)遍歷測(cè)量所有的子View
                if (currentLine == maxLine) {//到達(dá)最大行數(shù)時(shí),如果還有下一行,我們就不進(jìn)行顯示了
                    isMaxLine = true;
                    break;
                }
                child = mAdapter.getView(i, null, this);
                measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//獲取子控件大小
                childWidth = child.getMeasuredWidth();
                if (currentLineWidth == 0) {//已經(jīng)到達(dá)新的一行
                    views.put(currentLine, new SparseArray<>());//新建一個(gè)用來(lái)存放新的一行元素的集合
                }
                if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要換行
                    resultHeihgt += maxHeight + itemSpace;
                    maxHeights.put(currentLine, maxHeight);
                    currentLine++;
                    currentLineWidth = 0;
                    currentElement = 0;
                    i--;
                } else {
                    if (child.getMeasuredHeight() > maxHeight) {
                        maxHeight = child.getMeasuredHeight();//計(jì)算本行的最大高度,在layout時(shí),每行的高度就以最大高度為準(zhǔn)
                    }
                    views.get(currentLine).put(currentElement, child);//在測(cè)量完了,并且分析好這個(gè)元素的位置后,將其放入集合中,待之后onLayout時(shí)進(jìn)行擺放
                    currentElement++;
                    currentLineWidth += itemSpace + childWidth;
                }
            }
            if (resultHeihgt == 0) {//當(dāng)前item僅有一行
                resultHeihgt = maxHeight;
                maxHeights.put(0, maxHeight);
            } else {//當(dāng)前item不止一行,且未到達(dá)最大行數(shù)限制,到這里時(shí),需要補(bǔ)齊最后一行的高度數(shù)據(jù)
                if (!isMaxLine) {
                    resultHeihgt += maxHeight;//
                    maxHeights.put(currentLine, maxHeight);
                }
            }
            setMeasuredDimension(needWidth, resultHeihgt);//設(shè)置最終的寬高
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

通過onMeasure,我們通過每個(gè)item的寬高計(jì)算出了TagView的寬高,要顯示的行數(shù),每行的高度以及每行的元素及其所處的位置(存放到了views中),通過這些得到的內(nèi)容,接下來(lái)我們就要在onLayout中計(jì)算出每個(gè)item應(yīng)該擺放的具體位置了:

//在這個(gè)方法里我們要確定每個(gè)View擺放的位置
@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mAdapter != null && mAdapter.getCount() > 0) {
            View view;//當(dāng)前要進(jìn)行擺放的子View
            View lastView;//當(dāng)前擺放的子View左邊的View
            int childLeft, childRight, childTop, childBottom;
            for (int i = 0; i < views.size() && i < maxLine; i++) {//這個(gè)循環(huán)用來(lái)循環(huán)行數(shù)
                for (int j = 0; j < views.get(i).size(); j++) {//這個(gè)循環(huán)用來(lái)循環(huán)每行的列數(shù)
                    view = views.get(i).get(j);//第i行第j個(gè)元素
                    childLeft = 0;
                    for (int k = 0; k < j; k++) {//通過前面所有View的寬度相加,得到當(dāng)前子View的left位置
                        lastView = views.get(i).get(k);
                        childLeft += lastView.getMeasuredWidth() + itemSpace;
                    }
                    childRight = childLeft + view.getMeasuredWidth();
//確定子View上下的位置,根據(jù)gravity的不同(1是靠近父View頂部擺放,2是靠近父View底部擺放)
                    if (gravity == 1) {
                        childTop = 0;
                        for (int k = 0; k < i; k++) {//通過前面所有高度行數(shù)相加,得到最終的上邊位置
                            childTop += maxHeights.get(k) + itemSpace;
                        }
                    } else {
                        childTop = b - t;//b-t為最后一行的底部
                        for (int k = views.size() - 1 - i; k >= 0; k--) {//第一行的top位置是從最底部算起,后面所有行的高度+自身的高度值+行與行之間的空隙
                            childTop -= (maxHeights.get(k) + itemSpace);
                        }
                        childTop += itemSpace;//這里要加上多減去的空間
                    }

                    childBottom = childTop + view.getMeasuredHeight();
                    view.layout(childLeft, childTop, childRight, childBottom);
                    addView(view);
                }
            }
        }
    }

對(duì)于adapter,我們要給出一個(gè)可以進(jìn)行設(shè)置的方法:

public void setAdapter(Adapter adapter) {
        mAdapter = adapter;
        invalidate();
    }

使用的時(shí)候,我們這樣使用(采用的是效果圖中的數(shù)據(jù)):

String[] testTags = new String[]{"ssssss", "大家得人生", "ssdsjdj", "我們和小李都有", "放下一切", "大大大大大大多多"};
public void onCreate(Bundle saveInstanceStates){
...
TagView gv_tag = findViewById(R.layout.gv_tag);
gv_tag.setAdapter(new ArrayAdapter<>(context, R.layout.item_main_grid_sub_tag, R.id.tv_item, data.getTags()));//采用adapter方式比較靈活
...
}

完整代碼如下:

/**
 * Created by LiXiaoSong on 2017/7/10.
 * 自定義Tagview,用于顯示流布局
 */

public class TagView extends ViewGroup {
    private int itemSpace = 0;//item之間的間距
    private Adapter mAdapter;//這里傳入的adapter僅僅使用了其簡(jiǎn)單的功能
    private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(項(xiàng)目中暫時(shí)未用到垂直需求,所以暫時(shí)不需要)
    private SparseArray<SparseArray<View>> views;//用于記錄第幾行,第幾個(gè)item
    private SparseArray<Integer> maxHeights;//記錄每行的最大高度
    private int maxLine;//設(shè)置最大的行數(shù)
    private int gravity;//子View貼著上邊還是下邊(默認(rèn)上邊),1是上邊,2是下邊

    public TagView(Context context) {
        super(context);
        init(null);
    }

    public TagView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attributeSet) {
        views = new SparseArray<>();
        maxHeights = new SparseArray();
        if (attributeSet == null) {
            itemSpace = Utils.dp2px(getContext(), 5);
            maxLine = 10;// 默認(rèn)最大行數(shù)
        } else {
            TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
            itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
            gravity = array.getInt(R.styleable.TagView_gravity, 1);
            maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
            array.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int needWidth = MeasureSpec.getSize(widthMeasureSpec);
        int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
        int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
        int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
        if (mAdapter != null && mAdapter.getCount() > 0) {
            View child = null;
            int childWidth = 0;
            int currentLineWidth = 0;
            int currentLine = 0;//當(dāng)前行數(shù)
            int currentElement = 0;
            int maxHeight = 0;//當(dāng)前行數(shù)最大高度
            int resultHeihgt = 0;
            boolean isMaxLine = false;
            for (int i = 0; i < mAdapter.getCount(); i++) {//這里用來(lái)存放子View的元素
                if (currentLine == maxLine) {
                    isMaxLine = true;
                    break;
                }
                child = mAdapter.getView(i, null, this);
                measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//獲取子控件大小
                childWidth = child.getMeasuredWidth();
                if (currentLineWidth == 0) {//新的一行
                    views.put(currentLine, new SparseArray<>());
                }
                if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要換行
                    resultHeihgt += maxHeight + itemSpace;
                    maxHeights.put(currentLine, maxHeight);
                    currentLine++;
                    currentLineWidth = 0;
                    currentElement = 0;
                    i--;
                } else {
                    if (child.getMeasuredHeight() > maxHeight) {
                        maxHeight = child.getMeasuredHeight();
                    }
                    views.get(currentLine).put(currentElement, child);
                    currentElement++;
                    currentLineWidth += itemSpace + childWidth;
                }
            }
            if (resultHeihgt == 0) {//當(dāng)前item僅有一行
                resultHeihgt = maxHeight;
                maxHeights.put(0, maxHeight);
            } else {//如果不是,補(bǔ)齊最后一行的數(shù)據(jù)
                if (!isMaxLine) {
                    resultHeihgt += maxHeight;//
                    maxHeights.put(currentLine, maxHeight);
                }
            }
            setMeasuredDimension(needWidth, resultHeihgt);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mAdapter != null && mAdapter.getCount() > 0) {
            View view;
            View lastView;//它前面的View
            int childLeft, childRight, childTop, childBottom;
            for (int i = 0; i < views.size() && i < maxLine; i++) {
                for (int j = 0; j < views.get(i).size(); j++) {
                    view = views.get(i).get(j);//第i行第j個(gè)元素
                    childLeft = 0;
                    for (int k = 0; k < j; k++) {//通過前面所有View的寬度相加,得到最終的左邊位置
                        lastView = views.get(i).get(k);
                        childLeft += lastView.getMeasuredWidth() + itemSpace;
                    }
                    childRight = childLeft + view.getMeasuredWidth();
                    childTop = 0;
                    if (gravity == 1) {
                        for (int k = 0; k < i; k++) {//通過前面所有高度行數(shù)相加,得到最終的上邊位置
                            childTop += maxHeights.get(k) + itemSpace;
                        }
                    } else {
                        childTop = b - t;//設(shè)置一個(gè)底部
                        for (int k = views.size() - 1 - i; k >= 0; k--) {//通過前面所有高度行數(shù)相加,得到最終的上邊位置
                            childTop -= (maxHeights.get(k) + itemSpace);
                        }
                        childTop += itemSpace;
                    }

                    childBottom = childTop + view.getMeasuredHeight();
                    view.layout(childLeft, childTop, childRight, childBottom);
                    addView(view);
                }
            }
        }
    }

    public void setAdapter(Adapter adapter) {
        mAdapter = adapter;
        invalidate();
    }
}

本文到此結(jié)束,如果有什么問題,歡迎一起討論。

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

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,665評(píng)論 25 708
  • 樹雄心創(chuàng)大業(yè)江山添錦繡,立壯志寫春秋日月耀光華。水惟向下方成海,山不吟高可及天一杯土,尚巍然,問他銅雀荒臺(tái),何處尋...
    每個(gè)人的孟母堂閱讀 856評(píng)論 1 1
  • “崔佳兒!”“蘭玉石!”“吳優(yōu)越!”“王府依!”柯老師。我失敗了,競(jìng)選失敗了!我的好友蘭玉石卻入選了。 在Mun國(guó)...
    白嘉淺閱讀 317評(píng)論 0 0
  • 今天應(yīng)單位的工作部署,寫了一篇黨支部的《學(xué)習(xí)十九大心得體會(huì)》?,F(xiàn)在以個(gè)人的名義,繼續(xù)寫出心得體會(huì)!我可以...
    老區(qū)游子閱讀 622評(píng)論 0 3
  • 捧起《失樂園》,緣于與摯友分享《挪威的森林》讀后感后的推薦,時(shí)隔半年,好奇心一直驅(qū)使著我去捧讀,入手很久,終于...
    追尋真我閱讀 241評(píng)論 0 2