`
wyj365372704
  • 浏览: 13970 次
  • 性别: Icon_minigender_1
  • 来自: 江西
社区版块
存档分类
最新评论

Android中常见的热门标签的流式布局的实现

 
阅读更多

一、概述:
在日常的app使用中,我们会在android 的app中看见 热门标签等自动换行的流式布局,今天,我们就来看看如何

自定义一个类似热门标签那样的流式布局吧源码下载在下面最后给出

类似的自定义布局。下面我们就来详细介绍流式布局的应用特点以及用的的技术点:

1.流式布局的特点以及应用场景
    特点:当上面一行的空间不够容纳新的TextView时候,
    才开辟下一行的空间

  原理图:

  

    场景:主要用于关键词搜索或者热门标签等场景
2.自定义ViewGroup,重点重写下面两个方法

    1、onMeasure:测量子view的宽高,设置自己的宽和高

    2、onLayout:设置子view的位置

    onMeasure:根据子view的布局文件中属性,来为子view设置测量模式和测量值
    测量=测量模式+测量值;

    测量模式有3种:
    EXACTLY:表示设置了精确的值,一般当childView设置其宽、高为精确值、match_parent时,ViewGroup会将其设置为EXACTLY;
    AT_MOST:表示子布局被限制在一个最大值内,一般当childView设置其宽、高为wrap_content时,ViewGroup会将其设置为AT_MOST;
    UNSPECIFIED:表示子布局想要多大就多大,一般出现在AadapterView的item的heightMode中、ScrollView的childView的heightMode中;此种模式比较少见。
3.LayoutParams
    ViewGroup LayoutParams :每个 ViewGroup 对应一个 LayoutParams; 即 ViewGroup -> LayoutParams
    getLayoutParams 不知道转为哪个对应的LayoutParams ,其实很简单,就是如下:
    子View.getLayoutParams 得到的LayoutParams对应的就是 子View所在的父控件的LayoutParams;
    例如,LinearLayout 里面的子view.getLayoutParams ->LinearLayout.LayoutParams
    所以 咱们的FlowLayout 也需要一个LayoutParams,由于上面的效果图是子View的 margin,
    所以应该使用MarginLayoutParams。即FlowLayout->MarginLayoutParams

4.最后来看看实现的最终效果图:

二、热门标签的流式布局的实现:

1. 自定义热门标签的ViewGroup实现

  根据上面的技术分析,自定义类继承于ViewGroup,并重写 onMeasure和onLayout等方法。具体实现代码如下:

 

[plain] view plaincopy
 
 
  1. package com.czm.flowlayout;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.content.Context;  
  7. import android.util.AttributeSet;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. /**  
  11.  *   
  12.  * @author caizhiming  
  13.  * @created on 2015-4-13  
  14.  */  
  15. public class XCFlowLayout extends ViewGroup{  
  16.   
  17.     //存储所有子View  
  18.     private List<List<View>> mAllChildViews = new ArrayList<>();  
  19.     //每一行的高度  
  20.     private List<Integer> mLineHeight = new ArrayList<>();  
  21.       
  22.     public XCFlowLayout(Context context) {  
  23.         this(context, null);  
  24.         // TODO Auto-generated constructor stub  
  25.     }  
  26.     public XCFlowLayout(Context context, AttributeSet attrs) {  
  27.         this(context, attrs, 0);  
  28.         // TODO Auto-generated constructor stub  
  29.     }  
  30.     public XCFlowLayout(Context context, AttributeSet attrs, int defStyle) {  
  31.         super(context, attrs, defStyle);  
  32.         // TODO Auto-generated constructor stub  
  33.     }  
  34.     @Override  
  35.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  36.         // TODO Auto-generated method stub  
  37.           
  38.         //父控件传进来的宽度和高度以及对应的测量模式  
  39.         int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);  
  40.         int modeWidth = MeasureSpec.getMode(widthMeasureSpec);  
  41.         int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);  
  42.         int modeHeight = MeasureSpec.getMode(heightMeasureSpec);  
  43.           
  44.         //如果当前ViewGroup的宽高为wrap_content的情况  
  45.         int width = 0;//自己测量的 宽度  
  46.         int height = 0;//自己测量的高度  
  47.         //记录每一行的宽度和高度  
  48.         int lineWidth = 0;  
  49.         int lineHeight = 0;  
  50.           
  51.         //获取子view的个数  
  52.         int childCount = getChildCount();  
  53.         for(int i = 0;i < childCount; i ++){  
  54.             View child = getChildAt(i);  
  55.             //测量子View的宽和高  
  56.             measureChild(child, widthMeasureSpec, heightMeasureSpec);  
  57.             //得到LayoutParams  
  58.             MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();  
  59.             //子View占据的宽度  
  60.             int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;  
  61.             //子View占据的高度  
  62.             int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;  
  63.             //换行时候  
  64.             if(lineWidth + childWidth > sizeWidth){  
  65.                 //对比得到最大的宽度  
  66.                 width = Math.max(width, lineWidth);  
  67.                 //重置lineWidth  
  68.                 lineWidth = childWidth;  
  69.                 //记录行高  
  70.                 height += lineHeight;  
  71.                 lineHeight = childHeight;  
  72.             }else{//不换行情况  
  73.                 //叠加行宽  
  74.                 lineWidth += childWidth;  
  75.                 //得到最大行高  
  76.                 lineHeight = Math.max(lineHeight, childHeight);  
  77.             }  
  78.             //处理最后一个子View的情况  
  79.             if(i == childCount -1){  
  80.                 width = Math.max(width, lineWidth);  
  81.                 height += lineHeight;  
  82.             }  
  83.         }  
  84.         //wrap_content  
  85.         setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,  
  86.                 modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);  
  87.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  88.     }  
  89.       
  90.     @Override  
  91.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  92.         // TODO Auto-generated method stub  
  93.         mAllChildViews.clear();  
  94.         mLineHeight.clear();  
  95.         //获取当前ViewGroup的宽度  
  96.         int width = getWidth();  
  97.           
  98.         int lineWidth = 0;  
  99.         int lineHeight = 0;  
  100.         //记录当前行的view  
  101.         List<View> lineViews = new ArrayList<View>();  
  102.         int childCount = getChildCount();  
  103.         for(int i = 0;i < childCount; i ++){  
  104.             View child = getChildAt(i);  
  105.             MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();  
  106.             int childWidth = child.getMeasuredWidth();  
  107.             int childHeight = child.getMeasuredHeight();  
  108.               
  109.             //如果需要换行  
  110.             if(childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width){  
  111.                 //记录LineHeight  
  112.                 mLineHeight.add(lineHeight);  
  113.                 //记录当前行的Views  
  114.                 mAllChildViews.add(lineViews);  
  115.                 //重置行的宽高  
  116.                 lineWidth = 0;  
  117.                 lineHeight = childHeight + lp.topMargin + lp.bottomMargin;  
  118.                 //重置view的集合  
  119.                 lineViews = new ArrayList();  
  120.             }  
  121.             lineWidth += childWidth + lp.leftMargin + lp.rightMargin;  
  122.             lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);  
  123.             lineViews.add(child);  
  124.         }  
  125.         //处理最后一行  
  126.         mLineHeight.add(lineHeight);  
  127.         mAllChildViews.add(lineViews);  
  128.           
  129.         //设置子View的位置  
  130.         int left = 0;  
  131.         int top = 0;  
  132.         //获取行数  
  133.         int lineCount = mAllChildViews.size();  
  134.         for(int i = 0; i < lineCount; i ++){  
  135.             //当前行的views和高度  
  136.             lineViews = mAllChildViews.get(i);  
  137.             lineHeight = mLineHeight.get(i);  
  138.             for(int j = 0; j < lineViews.size(); j ++){  
  139.                 View child = lineViews.get(j);  
  140.                 //判断是否显示  
  141.                 if(child.getVisibility() == View.GONE){  
  142.                     continue;  
  143.                 }  
  144.                 MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();  
  145.                 int cLeft = left + lp.leftMargin;  
  146.                 int cTop = top + lp.topMargin;  
  147.                 int cRight = cLeft + child.getMeasuredWidth();  
  148.                 int cBottom = cTop + child.getMeasuredHeight();  
  149.                 //进行子View进行布局  
  150.                 child.layout(cLeft, cTop, cRight, cBottom);  
  151.                 left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;  
  152.             }  
  153.             left = 0;  
  154.             top += lineHeight;  
  155.         }  
  156.           
  157.     }  
  158.     /**  
  159.      * 与当前ViewGroup对应的LayoutParams  
  160.      */  
  161.     @Override  
  162.     public LayoutParams generateLayoutParams(AttributeSet attrs) {  
  163.         // TODO Auto-generated method stub  
  164.           
  165.         return new MarginLayoutParams(getContext(), attrs);  
  166.     }  
  167. }  

 

2.相关的布局文件:

引用自定义控件:

 

[plain] view plaincopy
 
 
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/container"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent" >  
  6.   
  7.     <com.czm.flowlayout.XCFlowLayout  
  8.         android:id="@+id/flowlayout"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" >  
  11.   
  12.     </com.czm.flowlayout.XCFlowLayout>  
  13.   
  14. </RelativeLayout>  

 

TextView的样式文件:

 

[plain] view plaincopy
 
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.     <solid android:color="#666666" />  
  4.     <corners android:radius="10dp" />  
  5.     <padding   
  6.         android:left="5dp"  
  7.         android:right="5dp"  
  8.         android:top="5dp"  
  9.         android:bottom="5dp"   
  10.         />  
  11.   
  12. </shape>  

 

三、使用该自定义布局控件类

最后,如何使用该自定义的热门标签控件类呢?很简单,请看下面实例代码:

 

[plain] view plaincopy
 
 
  1. package com.czm.flowlayout;  
  2.   
  3. import android.app.Activity;  
  4. import android.graphics.Color;  
  5. import android.os.Bundle;  
  6. import android.view.ViewGroup.LayoutParams;  
  7. import android.view.ViewGroup.MarginLayoutParams;  
  8. import android.widget.TextView;  
  9. /**  
  10.  *   
  11.  * @author caizhiming  
  12.  * @created on 2015-4-13  
  13.  */  
  14. public class MainActivity extends Activity {  
  15.   
  16.     private String mNames[] = {  
  17.             "welcome","android","TextView",  
  18.             "apple","jamy","kobe bryant",  
  19.             "jordan","layout","viewgroup",  
  20.             "margin","padding","text",  
  21.             "name","type","search","logcat"  
  22.     };  
  23.     private XCFlowLayout mFlowLayout;  
  24.     @Override  
  25.     protected void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.activity_main);  
  28.           
  29.         initChildViews();  
  30.           
  31.     }  
  32.     private void initChildViews() {  
  33.         // TODO Auto-generated method stub  
  34.         mFlowLayout = (XCFlowLayout) findViewById(R.id.flowlayout);  
  35.         MarginLayoutParams lp = new MarginLayoutParams(  
  36.                 LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
  37.         lp.leftMargin = 5;  
  38.         lp.rightMargin = 5;  
  39.         lp.topMargin = 5;  
  40.         lp.bottomMargin = 5;  
  41.         for(int i = 0; i < mNames.length; i ++){  
  42.             TextView view = new TextView(this);  
  43.             view.setText(mNames[i]);  
  44.             view.setTextColor(Color.WHITE);  
  45.             view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg));  
  46.             mFlowLayout.addView(view,lp);  
  47.         }  
  48.     }  
  49.   
  50. }  

 

四、源码下载

最后给出源码的下载:http://download.csdn.net/detail/jdsjlzx/8784571

 

这里引用另一个高手的实现,

 

摘要

新项目用到了一种全新布局————Android标签流式布局的功能,正好一直说给大家讲自定义控件的实现,今天就为大家讲一种android流式布局的实现。 
本文原创,转载请注明地址:http://blog.kymjs.com/

正文

 

在日常的app使用中,我们会在android 的app中看见热门标签等自动换行的流式布局,今天,我们就来看看如何自定义一个类似热门标签那样的流式布局吧(源码下载在下面最后给出)
OpenSourceLaboratory
这个控件并不是我实现的,代码是从网上搜流式布局找到的。我只是为大家讲解一下实现过程以及原理。

先看代码

publicclassFlowLayoutextendsViewGroup{privatefloatmVerticalSpacing;//每个item纵向间距privatefloatmHorizontalSpacing;//每个item横向间距publicFlowLayout(Contextcontext){super(context);}publicFlowLayout(Contextcontext,AttributeSetattrs){super(context,attrs);}publicvoidsetHorizontalSpacing(floatpixelSize){mHorizontalSpacing=pixelSize;}publicvoidsetVerticalSpacing(floatpixelSize){mVerticalSpacing=pixelSize;}@OverrideprotectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){intselfWidth=resolveSize(0,widthMeasureSpec);intpaddingLeft=getPaddingLeft();intpaddingTop=getPaddingTop();intpaddingRight=getPaddingRight();intpaddingBottom=getPaddingBottom();intchildLeft=paddingLeft;intchildTop=paddingTop;intlineHeight=0;//通过计算每一个子控件的高度,得到自己的高度for(inti=0,childCount=getChildCount();i<childCount;++i){ViewchildView=getChildAt(i);LayoutParamschildLayoutParams=childView.getLayoutParams();childView.measure(getChildMeasureSpec(widthMeasureSpec,paddingLeft+paddingRight,childLayoutParams.width),getChildMeasureSpec(heightMeasureSpec,paddingTop+paddingBottom,childLayoutParams.height));intchildWidth=childView.getMeasuredWidth();intchildHeight=childView.getMeasuredHeight();lineHeight=Math.max(childHeight,lineHeight);if(childLeft+childWidth+paddingRight>selfWidth){childLeft=paddingLeft;childTop+=mVerticalSpacing+lineHeight;lineHeight=childHeight;}else{childLeft+=childWidth+mHorizontalSpacing;}}intwantedHeight=childTop+lineHeight+paddingBottom;setMeasuredDimension(selfWidth,resolveSize(wantedHeight,heightMeasureSpec));}@OverrideprotectedvoidonLayout(booleanchanged,intl,intt,intr,intb){intmyWidth=r-l;intpaddingLeft=getPaddingLeft();intpaddingTop=getPaddingTop();intpaddingRight=getPaddingRight();intchildLeft=paddingLeft;intchildTop=paddingTop;intlineHeight=0;//根据子控件的宽高,计算子控件应该出现的位置。for(inti=0,childCount=getChildCount();i<childCount;++i){ViewchildView=getChildAt(i);if(childView.getVisibility()==View.GONE){continue;}intchildWidth=childView.getMeasuredWidth();intchildHeight=childView.getMeasuredHeight();lineHeight=Math.max(childHeight,lineHeight);if(childLeft+childWidth+paddingRight>myWidth){childLeft=paddingLeft;childTop+=mVerticalSpacing+lineHeight;lineHeight=childHeight;}childView.layout(childLeft,childTop,childLeft+childWidth,childTop+childHeight);childLeft+=childWidth+mHorizontalSpacing;}}}

从控件创建过程说起

  1. 当这个流式布局在被加载如内存并显示在屏幕上这一过程中,首先会调用view.measure(w,h)这个方法,表示测量view的宽度与高度,其中参数w与h分别表示这个控件的父控件的宽高。
  2. 在view.measure()方法的调用过程中又会调用view本身的一个回调方法,onMeasure(),这个是view自身的一个回调方法,用于让开发者在自定义View的时候重新计算自身的大小。一般会在这个方法中循环遍历,计算出这个控件的全部子孙控件的宽高。
  3. 在View的宽高计算完成以后,考虑将这个控件显示到屏幕的指定位置上,此时view的onLayout()方法会被调用。 一般同时会在这个方法中计算出全部子孙控件在这个控件中的位置。
    可能基本流程有些枯燥,接下来结合代码看看。

流布局的实现

看到onMeasure()方法中的这段: //通过计算每一个子控件的高度,得到自己的高度

for(inti=0,childCount=getChildCount();i<childCount;++i){ViewchildView=getChildAt(i);LayoutParamschildLayoutParams=childView.getLayoutParams();childView.measure(getChildMeasureSpec(widthMeasureSpec,paddingLeft+paddingRight,childLayoutParams.width),getChildMeasureSpec(heightMeasureSpec,paddingTop+paddingBottom,childLayoutParams.height));intchildWidth=childView.getMeasuredWidth();intchildHeight=childView.getMeasuredHeight();lineHeight=Math.max(childHeight,lineHeight);if(childLeft+childWidth+paddingRight>selfWidth){childLeft=paddingLeft;childTop+=mVerticalSpacing+lineHeight;lineHeight=childHeight;}else{childLeft+=childWidth+mHorizontalSpacing;}}

首先通过循环,遍历这个控件的所有子控件,同时调用子控件的measure()方法,这时measure方法的两个参数是控件能给这个子控件的最大宽高(我们都知道的,子控件再大,显示的大小也不能比父控件还大)。这里getChildMeasureSpec()方法的作用是用来计算一个合适子视图的尺寸大小(宽度或者高度),结合我们从子视图的LayoutParams所给出的MeasureSpec信息来获取最合适的结果。比如,如果这个View知道自己的大小尺寸(因为它本身的MeasureSpec的model为Exactly,)并且子视图的大小恰好跟父窗口一样大,父窗口必须用给定的大小去layout子视图 
参数含义:spec 父窗口传递给子视图的大小和模式
padding 父窗口的边距,也就是xml中的android:padding
childDimension 子视图想要绘制的准确大小,但最终不一定绘制此值

当得到了每一个子控件的大小以后,再要计算自己的宽高就简单了。
int wantedHeight = childTop + lineHeight + paddingBottom;

同理,在onLayout中的这一句

for(inti=0,childCount=getChildCount();i<childCount;++i){ViewchildView=getChildAt(i);if(childView.getVisibility()==View.GONE){continue;}intchildWidth=childView.getMeasuredWidth();intchildHeight=childView.getMeasuredHeight();lineHeight=Math.max(childHeight,lineHeight);if(childLeft+childWidth+paddingRight>myWidth){childLeft=paddingLeft;childTop+=mVerticalSpacing+lineHeight;lineHeight=childHeight;}childView.layout(childLeft,childTop,childLeft+childWidth,childTop+childHeight);childLeft+=childWidth+mHorizontalSpacing;}

首先通过循环遍历,控制每个item子控件的显示位置,如果当前行还能放得下一个item,就放到当前行,如果放不下就放到下一行的最左边。
最终,遍历完成,也就相当于把自己的位置显示完成了。

效果截图

OpenSourceLaboratory

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics