Android 自定義ViewGroup——FlowLayout流式標簽

最近一直在學習自定義View和自定義ViewGroup的東西析校,今天沒事干就研究了一下FlowLayout掐松,記錄下實現步驟,參考自鴻洋博客

AndroidStudio使用

在根projcet的build.gradle中添加.

maven { url 'https://jitpack.io' }

在項目的build.gradle添加:

compile 'com.github.superSp:FlowLayout:1.0'

github有源碼查看

效果圖 自適應

圖片.png

效果圖 固定大小

圖片.png

使用方法——靜態(tài)添加

<lsp.com.library.FlowLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        style="@style/text_flag_01"
        android:text="Welcome" />

    <TextView
        style="@style/text_flag_01"
        android:text="IT工程師" />

    <TextView
        style="@style/text_flag_01"
        android:text="學習ing" />

    <TextView
        style="@style/text_flag_01"
        android:text="戀愛ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="戀愛ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="掙錢ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="努力ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="I thick i can" />

</lsp.com.library.FlowLayout>

style文件:

  <style name="text_flag_01">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">5dp</item>
        <item name="android:background">@drawable/flag_01</item>
    </style>

drawable文件:

樣式1(flag_01)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#7690A5"/>

    <corners android:radius="5dp"/>

    <padding android:bottom="2dp"
        android:left="2dp"
        android:right="2dp"
        android:top="2dp"/>
</shape>

樣式2(flag_02)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#E7E7E7" >
    </solid>
    <corners
        android:radius="30dp"
        />

    <padding
        android:bottom="2dp"
        android:left="10dp"
        android:right="10dp"
        android:top="2dp" />
</shape>

按自己喜好設置就行~~

使用方法——動態(tài)添加


        FlowLayout flowLayout = new FlowLayout(this);

        flowLayout.initData(Arrays.asList("Welcome","IT工程師","學習ing","戀愛ing"
        ,"掙錢ing","努力ing","I thick i can"));

        setContentView(flowLayout);

initData方法

public void initData(List<String> list)
public void initData(List<String> list, int margin, int drawable) 

添加點擊事件

 flowLayout.setOnTabClickListener(new FlowLayout.IOnTabClickListener() {

            @Override
            public void onTabClick(int position, TextView textView) {
                Toast.makeText(Test.this,position+" "+textView.getText(),Toast.LENGTH_SHORT).show();
            }
        });
        setContentView(flowLayout);

實現思路

構造方法
    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);
    }
子view支持margin屬性
 @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

onMeasure方法

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        //測量子view的大小
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        //最終的寬和高
        int width = 0;
        int height = 0;
        //記錄每一行的寬和高
        int lineWidth = 0;
        //子view數量
        int cCount = getChildCount();
        View cView;
        MarginLayoutParams params;
        int cWidth, cHeight;

        for (int i = 0; i < cCount; i++) {
            cView = getChildAt(i);
            params = (MarginLayoutParams) cView.getLayoutParams();
            cWidth = cView.getMeasuredWidth() + params.leftMargin + params.rightMargin;
            cHeight = cView.getMeasuredHeight() + params.topMargin + params.bottomMargin;

            ViewBean viewBean = new ViewBean();
          
            if (lineWidth + cWidth < widthSize) {

                lineWidth += cWidth;

                height = Math.max(height, cHeight);

                width = Math.max(lineWidth, width);

            } else {

                width = Math.max(lineWidth, width);

                height += cHeight;

                lineWidth = cWidth;

            }

            viewBean.setLeft(lineWidth - cWidth + params.leftMargin);
            viewBean.setTop(height - cHeight + params.topMargin);
            viewBean.setRight(lineWidth - params.rightMargin);
            viewBean.setBottom(height - params.bottomMargin);

            list.add(viewBean);

        }
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heightMode == MeasureSpec.EXACTLY ? heightSize : height);
    }
onLayout方法
 @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            getChildAt(i).layout(list.get(i).getLeft(), list.get(i).getTop(), list.get(i).getRight(), list.get(i).getBottom());
        }

    }
ViewBean方法
private class ViewBean {
        private int left;
        private int right;
        private int top;
        private int bottom;

        public int getLeft() {
            return left;
        }

        public void setLeft(int left) {
            this.left = left;
        }

        public int getRight() {
            return right;
        }

        public void setRight(int right) {
            this.right = right;
        }

        public int getTop() {
            return top;
        }

        public void setTop(int top) {
            this.top = top;
        }

        public int getBottom() {
            return bottom;
        }

        public void setBottom(int bottom) {
            this.bottom = bottom;
        }
    }
動態(tài)填充數據實現
 public void initData(List<String> list) {
        ViewGroup.MarginLayoutParams pa = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT,
                ViewGroup.MarginLayoutParams.WRAP_CONTENT);
        int size = list.size();
        for (int i = 0; i < size; i++) {
            TextView tv = new TextView(getContext());
            tv.setText(list.get(i));
            addView(tv, pa);
            ((ViewGroup.MarginLayoutParams) tv.getLayoutParams()).setMargins(DensityUtils.dp2px(getContext(), 5), DensityUtils.dp2px(getContext(), 5),
                    DensityUtils.dp2px(getContext(), 5), DensityUtils.dp2px(getContext(), 5));
            tv.setBackgroundResource(R.drawable.flag_01);
        }
    }

添加點擊事件

public interface IOnTabClickListener {
        void onTabClick(int position, TextView textView);
    }

private void setOnclick(final int position, final TextView textView) {
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                iOnTabClickListener.onTabClick(position, textView);
            }
        });
    }
后記

比較難理解的部分應該就是onMeasure了。。當設置wrap的時候找到寬度最大的值几睛。。并且設置每個view的坐標.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末粤攒,一起剝皮案震驚了整個濱河市所森,隨后出現的幾起案子,更是在濱河造成了極大的恐慌夯接,老刑警劉巖焕济,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異盔几,居然都是意外死亡晴弃,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來上鞠,“玉大人际邻,你說我怎么就攤上這事∑旃” “怎么了枯怖?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長能曾。 經常有香客問我,道長肿轨,這世上最難降的妖魔是什么寿冕? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮椒袍,結果婚禮上驼唱,老公的妹妹穿的比我還像新娘。我一直安慰自己驹暑,他們只是感情好玫恳,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著优俘,像睡著了一般京办。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上帆焕,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天惭婿,我揣著相機與錄音,去河邊找鬼叶雹。 笑死财饥,一個胖子當著我的面吹牛,可吹牛的內容都是我干的折晦。 我是一名探鬼主播钥星,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼满着!你這毒婦竟也來了谦炒?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤漓滔,失蹤者是張志新(化名)和其女友劉穎编饺,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體响驴,經...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡透且,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秽誊。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡鲸沮,死狀恐怖,靈堂內的尸體忽然破棺而出锅论,到底是詐尸還是另有隱情讼溺,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布最易,位于F島的核電站怒坯,受9級特大地震影響,放射性物質發(fā)生泄漏藻懒。R本人自食惡果不足惜剔猿,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嬉荆。 院中可真熱鬧归敬,春花似錦、人聲如沸鄙早。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽限番。三九已至舱污,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間扳缕,已是汗流浹背慌闭。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留躯舔,地道東北人驴剔。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像粥庄,于是被迫代替她去往敵國和親丧失。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,139評論 25 707
  • afinalAfinal是一個android的ioc惜互,orm框架 https://github.com/yangf...
    passiontim閱讀 15,431評論 2 45
  • 阿貍布讹,我最愛的東西!很有心的他給我買了好多關于阿貍的東西训堆,漫畫書描验,涂鴉本,玩偶坑鱼,都是阿貍膘流!可能在他的心里絮缅,我...
    全世界我想遇見你閱讀 265評論 0 0
  • 很認真的想寫點什么彭谁,卻思緒萬千吸奴。 似乎千軍萬馬奔過心頭, 仿佛百丈冰原突然倒塌缠局, 好像宇宙黑洞離奇吸引则奥。 人的內心...
    知魚之樂V閱讀 2,538評論 2 2
  • 2017.8.31 八月的最后一天 好的壞的就都留在八月吧 聽著七尾旅人的【八月】 抬頭瞇著眼透過樹葉看陽光 低頭...
    哄小轟閱讀 258評論 1 3