一個(gè)簡(jiǎn)單的標(biāo)簽流布局

繼承ViewGroup實(shí)現(xiàn)一個(gè)簡(jiǎn)單的自動(dòng)換行流布局
可實(shí)現(xiàn)同比等寬旷太、自適應(yīng)寬度兩種樣式
源碼:https://github.com/Beckboy/FlowLayoutTextViewDome.git

前段時(shí)間在工作中有遇到瀑布流布局,給自己造成一定困擾销睁。
通過(guò)這段時(shí)間的實(shí)用和總結(jié)供璧,自己也相應(yīng)的封裝了一套,會(huì)在接下來(lái)的一段時(shí)間不斷完善冻记,方便今后能直接使用睡毒。

標(biāo)簽流.gif

步驟

  1. 繼承ViewGroup;
  2. 復(fù)寫(xiě)onMeasure()冗栗,計(jì)算每個(gè)子view的寬和高演顾,根據(jù)全部子view的寬和高,獲取整個(gè)布局的寬和高隅居;
  3. 復(fù)寫(xiě)onLayout()钠至,計(jì)算每個(gè)子view的位置并設(shè)置布局;
  4. 提供獲取行數(shù)的方法getLines()胎源;
  5. 提供獲取當(dāng)前行高度的方法getCloseHeight()棉钧;

實(shí)現(xiàn)

  • 繼承ViewGroup
public class FlowLayout extends ViewGroup
  • 初始化數(shù)據(jù)源
  //存儲(chǔ)當(dāng)前ViewGroup的所有view,在Activity中直接用addView(View view)添加涕蚤;
  private List<List<View>> mAllViews = new ArrayList<List<View>>();
  //把每一行數(shù)據(jù)的高度存儲(chǔ)到List
  private List<Integer> mHeightList = new ArrayList<Integer>();
  • 復(fù)寫(xiě)onLayout
  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    mAllViews.clear();
    mHeightList.clear();
    int width = getWidth();
    int overWidth = 0; //每一行view所占據(jù)的總寬度margin宪卿,padding
    int overHeight = 0; //每一個(gè)view所占據(jù)的總高度
    List<View> lineViews = new ArrayList<View>();
    int viewCount = getChildCount(); //所有View的總數(shù)量
    for (int i = 0;i < viewCount ; i++){
      View child = getChildAt(i); //每一個(gè)子View
      MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
      int childViewWidth = child.getMeasuredWidth();
      int childViewHeight = child.getMeasuredHeight();
      //當(dāng)前View超過(guò)一行時(shí),換行處理
      if (childViewWidth + overWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight()){ //換行判斷
        mHeightList.add(overHeight);
        mAllViews.add(lineViews);
        //重置行寬和行高
        overWidth = 0;
        overHeight = childViewHeight + lp.topMargin + lp.bottomMargin;
        //重置我們的View集合
        lineViews = new ArrayList<View>();
      }
      overWidth += childViewWidth + lp.leftMargin + lp.rightMargin;
      overHeight = Math.max(overHeight,childViewHeight + lp.topMargin +lp.bottomMargin);
      lineViews.add(child);
    }

    //處理最后一行
    mHeightList.add(overHeight);
    mAllViews.add(lineViews);
    //設(shè)置每一個(gè)子View的位置
    int childLeft = getPaddingLeft();
    int childTop = getPaddingTop();
    //當(dāng)前行數(shù)
    int linesNum = mAllViews.size();
    for (int i = 0; i < linesNum; i++){
      //當(dāng)前行的所有view
      lineViews = mAllViews.get(i);
      overHeight = mHeightList.get(i);
      for (int j = 0;j < lineViews.size();j++){
        View child = lineViews.get(j);
        //判斷當(dāng)前View的狀態(tài)
        if (child.getVisibility() == View.GONE){
          continue;
        }
        MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        int lc = childLeft + lp.leftMargin;
        int tc = childTop + lp.topMargin;
        int rc = lc + child.getMeasuredWidth();
        int bc = tc + child.getMeasuredHeight();
        child.layout(lc,tc,rc,bc); //為子View進(jìn)行布局
        childLeft +=child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
      }
      childLeft = getPaddingLeft();
      childTop += overHeight;
    }
  }

-復(fù)寫(xiě)onMeasure

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
    int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
    int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    //wrap_content模式下的寬度和高度
    int width = 0;
    int height = 0;
    //記錄每一行的寬度和高度
    int lineWidth = 0;
    int lineHeight = 0;
    //獲取內(nèi)容的View元素個(gè)數(shù)
    int cCount = getChildCount();
    for (int i = 0; i < cCount; i++){
      View child = getChildAt(i);
      //測(cè)量子View的寬度和高度
      measureChild(child,widthMeasureSpec,heightMeasureSpec);
      //得到LayoutParams
      MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
      //子View占據(jù)的寬度
      int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
      //子View占據(jù)的高度
      int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
      //換行處理
      if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()){
        //對(duì)比得到的最大寬度
        width = Math.max(width,lineWidth);
        //重置
        lineWidth = childWidth;
        //記錄行高
        height += lineHeight;
        lineHeight = childHeight;
      }else {
        lineWidth += childWidth;
        //獲取當(dāng)前行最大的高度
        lineHeight = Math.max(lineHeight,childHeight);
      }
      if (i == cCount - 1){ //如果是最后一個(gè)控件
        width = Math.max(lineWidth,width);
        height +=lineHeight;
      }
    }

    setMeasuredDimension(
        modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width + getPaddingLeft() + getPaddingRight(),
        modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop() + getPaddingBottom());
  }
  • 獲取指定行數(shù)的高度
  public int getCloseHeight(int lines){
    int hh = 0;
    if (lines > mHeightList.size()){
      lines = mHeightList.size();
    }
    for (int i = 0; i < lines;i++){
       hh += mHeightList.get(i);
    }
    return hh;
  }
  • 獲取總行數(shù)
  public int getLines(){
      return mAllViews.size();
  }

使用

  • 初始化數(shù)據(jù)源
    // 數(shù)據(jù)源
    private String[] collegData = new String[]{"清華大學(xué)","北京大學(xué)","復(fù)旦大學(xué)","浙江大學(xué)","南開(kāi)大學(xué)","同濟(jì)大學(xué)"
                        ,"蘇州大學(xué)","吉林大學(xué)","哈佛大學(xué)","斯坦福大學(xué)","麻省理工大學(xué)","斯坦福大學(xué)","加州理工學(xué)院"};

  • 初始化子布局
    //寬高
    private int width = ViewGroup.LayoutParams.WRAP_CONTENT;
    private int height = ViewGroup.LayoutParams.WRAP_CONTENT;
  • 在代碼中動(dòng)態(tài)添加子view
    /**
     * 初始化瀑布流列表
     */
    private void initData() {
        for (String colleg : collegData){
            loadFlowCircleList(colleg);
        }
    }

    /**
     * 加載流標(biāo)簽
     */
    private void loadFlowCircleList(String colleg) {
        CheckBox cbTag = (CheckBox) getLayoutInflater().inflate(R.layout.item_topic_tag, mFlow, false);
        cbTag.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_bg_check_circle));
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(width,height);
        lp.leftMargin = 20; //左間距
        lp.rightMargin = 20; //右間距
        lp.topMargin = 40; //上間距
        cbTag.setLayoutParams(lp);
        cbTag.setText(colleg);
        mFlow.addView(cbTag);
    }
  • 設(shè)置子view的點(diǎn)擊事件
public void onclick(View view) {
        mFlow.removeAllViews();
        switch (view.getId()){
            case R.id.btn_left: //加載自適應(yīng)流布局
                width = ViewGroup.LayoutParams.WRAP_CONTENT;
                break;
            case R.id.btn_right: //加載等寬流布局
                int column = 3; //列數(shù)
                int max_width = getWindowManager().getDefaultDisplay().getWidth(); //獲取屏幕寬度
                width = (max_width - 40 * column)/column;
                break;
        }
        initData();
    }
  • 布局文件
    FlowLayout布局文件
    <com.example.hunter_j.flowlayoutdemo.view.FlowLayout
        android:id="@+id/flowlayouot"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"/>

??子view布局文件

<CheckBox
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="54px"
    android:paddingTop="14px"
    android:paddingBottom="14px"
    android:paddingLeft="20px"
    android:paddingRight="20px"
    android:gravity="center"
    android:textSize="13sp"
    android:button="@null"
    android:textColor="@drawable/selector_color_txt">
</CheckBox>

??xml設(shè)置子view字體赞季、背景變色自動(dòng)

<!--drawable資源文件:selector_bg_check_circle-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_checked="false" >
       <shape android:shape="rectangle">
           <solid android:color="#f3f6f7"/>
           <corners android:radius="50px"/>
       </shape>
   </item>
   <item android:state_checked="true">
       <shape android:shape="rectangle">
           <solid android:color="#ffc84a"/>
           <corners android:radius="50px"/>
       </shape>
   </item>
</selector>

<!--drawable資源文件:selector_color_txt-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="false" android:state_enabled="true" android:state_pressed="false"
       android:color="@drawable/color_cdac8d" />
   <item android:state_enabled="false" android:color="@drawable/color_cdac8d" />
   <item android:state_pressed="true" android:color="@drawable/color_f9" />
   <item android:state_focused="true"  android:color="@drawable/color_f9" />
</selector>

<!--color資源文件-->
<resources>
   <!-- 字體顏色的選擇器 -->
   <drawable name="color_f9">#F9F9F9</drawable>
   <drawable name="color_cdac8d">#CDAC8D</drawable>
</resources>

源碼:

源碼:https://github.com/Beckboy/FlowLayoutTextViewDome.git

新手上路愧捕,歡迎同學(xué)們吐槽評(píng)論奢驯,如果你覺(jué)得對(duì)你有幫助
那么就留個(gè)言或者點(diǎn)下喜歡吧(^-^)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末申钩,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子瘪阁,更是在濱河造成了極大的恐慌撒遣,老刑警劉巖邮偎,帶你破解...
    沈念sama閱讀 219,589評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異义黎,居然都是意外死亡禾进,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門(mén)廉涕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)泻云,“玉大人,你說(shuō)我怎么就攤上這事狐蜕〕璐浚” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,933評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵层释,是天一觀的道長(zhǎng)婆瓜。 經(jīng)常有香客問(wèn)我,道長(zhǎng)贡羔,這世上最難降的妖魔是什么廉白? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,976評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮乖寒,結(jié)果婚禮上猴蹂,老公的妹妹穿的比我還像新娘。我一直安慰自己宵统,他們只是感情好晕讲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布润歉。 她就那樣靜靜地躺著帆赢,像睡著了一般。 火紅的嫁衣襯著肌膚如雪海渊。 梳的紋絲不亂的頭發(fā)上痊班,一...
    開(kāi)封第一講書(shū)人閱讀 51,775評(píng)論 1 307
  • 那天勤婚,我揣著相機(jī)與錄音,去河邊找鬼涤伐。 笑死馒胆,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的凝果。 我是一名探鬼主播祝迂,決...
    沈念sama閱讀 40,474評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼器净!你這毒婦竟也來(lái)了型雳?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,359評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎纠俭,沒(méi)想到半個(gè)月后沿量,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,854評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡冤荆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評(píng)論 3 338
  • 正文 我和宋清朗相戀三年朴则,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片钓简。...
    茶點(diǎn)故事閱讀 40,146評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡乌妒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出外邓,到底是詐尸還是另有隱情芥被,我是刑警寧澤,帶...
    沈念sama閱讀 35,826評(píng)論 5 346
  • 正文 年R本政府宣布坐榆,位于F島的核電站拴魄,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏席镀。R本人自食惡果不足惜匹中,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望豪诲。 院中可真熱鬧顶捷,春花似錦、人聲如沸屎篱。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,029評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)交播。三九已至重虑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間秦士,已是汗流浹背缺厉。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,153評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留隧土,地道東北人提针。 一個(gè)月前我還...
    沈念sama閱讀 48,420評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像曹傀,于是被迫代替她去往敵國(guó)和親辐脖。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評(píng)論 2 356

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