Android 自定義帶間距的自動(dòng)換行控件

很多的搜索界面都會有這樣的布局:標(biāo)簽依次順序排列,當(dāng)一行放不下后自動(dòng)移動(dòng)到下一行晦毙,最近公司項(xiàng)目也要做一個(gè)這樣的效果来惧,網(wǎng)上搜了搜看到有很多類似的,但是因?yàn)楣镜囊茉O(shè)置間隔距離心例,所以決定自己寫一個(gè)宵凌,效果圖如下:


效果圖

AutoLinefeedLayout

public class AutoLinefeedLayout extends ViewGroup {

    /**
     * 子view左右間距
     */
    private int mHorizontalSpacing;
    /**
     * 上下行距離
     */
    private int mVerticalSpacing;


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

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

    public AutoLinefeedLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (attrs != null) {
            TypedArray array = context.obtainStyledAttributes(attrs,
                    R.styleable.AutoLayout);

            mHorizontalSpacing = array.getDimensionPixelOffset(
                    R.styleable.AutoLayout_horizontalSpacing, 0);
            mVerticalSpacing = array.getDimensionPixelOffset(
                    R.styleable.AutoLayout_verticalSpacing, 0);
            array.recycle();

            if (mHorizontalSpacing < 0) mHorizontalSpacing = 0;
            if (mVerticalSpacing < 0) mVerticalSpacing = 0;
        }
    }

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

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
        }


        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthMode != MeasureSpec.EXACTLY) {
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(
                    getAutoLinefeedWidth(width), widthMode);
        }

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode != MeasureSpec.EXACTLY) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                    getAutoLinefeedHeight(width), heightMode);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    /**
     * 自動(dòng)換行 計(jì)算需要的寬度
     *
     * @param width 可用寬度
     * @return 需要的寬度
     */
    private int getAutoLinefeedWidth(int width) {
        int totalWidth = getPaddingLeft() + getPaddingRight();

        for (int i = 0; i < getChildCount(); i++) {
            if (i > 0) totalWidth += mHorizontalSpacing;
            View child = getChildAt(i);
            int childWidth = child.getMeasuredWidth();
            totalWidth += childWidth;
            if (totalWidth >= width) {
                totalWidth = width;
                break;
            }
        }

        return totalWidth;
    }

    /**
     * 自動(dòng)換行 計(jì)算需要的高度
     *
     * @param width 可用寬度
     * @return 需要的高度
     */
    private int getAutoLinefeedHeight(int width) {

        //一行最大可用寬度
        int lineWidth = width - getPaddingLeft() - getPaddingRight();
        //剩余可用寬度
        int availableLineWidth = lineWidth;
        //需要的高度
        int totalHeight = getPaddingTop() + getPaddingBottom();
        int lineChildIndex = 0;
        //本行最大高度
        int lineMaxHeight = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            //這個(gè)child需要的寬度  如果不是第一位的 那么需要加上間距
            //這里是用來判斷需不需要換行
            int needWidth = i == 0 ? childWidth : (childWidth + mHorizontalSpacing);
            //如果剩余可用寬度小于需要的長度 那么換行
            if (availableLineWidth < needWidth) {
                totalHeight = totalHeight + lineMaxHeight;
                if (i > 0) totalHeight += mVerticalSpacing;
                availableLineWidth = lineWidth;
                lineMaxHeight = 0;
                lineChildIndex = 0;
            }
            //這個(gè)child需要的寬度  如果不是第一位的 那么需要加上間距
            int realNeedWidth = lineChildIndex == 0 ? childWidth : (childWidth + mHorizontalSpacing);
            lineMaxHeight = Math.max(childHeight, lineMaxHeight);
            availableLineWidth = availableLineWidth - realNeedWidth;
            lineChildIndex++;
        }

        totalHeight = totalHeight + lineMaxHeight;
        return totalHeight;
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        layout();
    }


    private void layout() {

        int count = getChildCount();
        int childLeft = getPaddingLeft();
        int childTop = getPaddingTop();
        int lineWidth = getMeasuredWidth() - getPaddingRight() - getPaddingLeft();
        int availableLineWidth = lineWidth;
        int lineChildIndex = 0;
        //一行的最大高度
        int lineMaxHeight = 0;
        for (int i = 0; i < count; i++) {

            View child = getChildAt(i);

            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            int needWidth = i == 0 ? childWidth : (childWidth + mHorizontalSpacing);

            if (availableLineWidth < needWidth) {
                availableLineWidth = lineWidth;
                childTop += lineMaxHeight;
                if (i > 0) childTop += mVerticalSpacing;
                lineMaxHeight = 0;
                childLeft = getPaddingLeft();
                lineChildIndex = 0;
            }

            int realNeedWidth = lineChildIndex == 0 ? childWidth : (childWidth + mHorizontalSpacing);

            lineMaxHeight = Math.max(lineMaxHeight, childHeight);
            child.layout(childLeft + realNeedWidth - childWidth, childTop, childLeft + realNeedWidth, childTop + childHeight);
            availableLineWidth -= realNeedWidth;
            childLeft += realNeedWidth;
            lineChildIndex++;
        }
    }

    public int getHorizontalSpacing() {
        return mHorizontalSpacing;
    }

    public void setHorizontalSpacing(int horizontalSpacing) {
        mHorizontalSpacing = horizontalSpacing;
    }

    public int getVerticalSpacing() {
        return mVerticalSpacing;
    }

    public void setVerticalSpacing(int verticalSpacing) {
        mVerticalSpacing = verticalSpacing;
    }
}

attrs:

    <declare-styleable name="AutoLinefeedLayout">
        <attr name="horizontalSpacing" format="dimension"/>
        <attr name="verticalSpacing" format="dimension"/>
    </declare-styleable>

使用
activity中

        AutoLinefeedLayout autoLinefeedLayout =  findViewById(R.id.auto_linefeed_layout);
        String[] labels = {"微信", "QQ", "網(wǎng)易云音樂", "支付寶", "UC瀏覽器", "鐵路12306", "釘釘", "攜程旅游", "手機(jī)淘寶", "58同城", "安居客", "滴滴出行"};
        for (String label : labels) {
            TextView textView = new TextView(getContext());
            textView.setBackgroundColor(Color.BLACK);
            textView.setTextColor(Color.WHITE);
            textView.setText(label);
            autoLinefeedLayout .addView(textView);
        }

xml

    <com.ph.test.test.weight.AutoLinefeedLayout
        android:id="@+id/auto_linefeed_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:horizontalSpacing="10dp"
        app:verticalSpacing="10dp"/>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市止后,隨后出現(xiàn)的幾起案子瞎惫,更是在濱河造成了極大的恐慌,老刑警劉巖译株,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瓜喇,死亡現(xiàn)場離奇詭異,居然都是意外死亡歉糜,警方通過查閱死者的電腦和手機(jī)乘寒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來匪补,“玉大人伞辛,你說我怎么就攤上這事『蝗保” “怎么了蚤氏?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長喳逛。 經(jīng)常有香客問我瞧捌,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任姐呐,我火速辦了婚禮殿怜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘曙砂。我一直安慰自己头谜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布鸠澈。 她就那樣靜靜地躺著柱告,像睡著了一般。 火紅的嫁衣襯著肌膚如雪笑陈。 梳的紋絲不亂的頭發(fā)上际度,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天,我揣著相機(jī)與錄音涵妥,去河邊找鬼乖菱。 笑死,一個(gè)胖子當(dāng)著我的面吹牛蓬网,可吹牛的內(nèi)容都是我干的窒所。 我是一名探鬼主播,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼帆锋,長吁一口氣:“原來是場噩夢啊……” “哼吵取!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起锯厢,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤皮官,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后哲鸳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體臣疑,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年徙菠,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了讯沈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,498評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡婿奔,死狀恐怖缺狠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情萍摊,我是刑警寧澤挤茄,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站冰木,受9級特大地震影響穷劈,放射性物質(zhì)發(fā)生泄漏笼恰。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一歇终、第九天 我趴在偏房一處隱蔽的房頂上張望社证。 院中可真熱鬧,春花似錦评凝、人聲如沸追葡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽宜肉。三九已至,卻和暖如春翎碑,著一層夾襖步出監(jiān)牢的瞬間谬返,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工杈女, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留朱浴,地道東北人吊圾。 一個(gè)月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓达椰,卻偏偏與公主長得像,于是被迫代替她去往敵國和親项乒。 傳聞我的和親對象是個(gè)殘疾皇子啰劲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評論 2 359