瀑布流StaggeredGridView

  关于Android瀑布流控件相关学习资源,github上有两个资源,可以供学习者膜拜。

1.https://github.com/maurycyw/StaggeredGridView    此链接有图片加载功能,但功能相对简单些。

2.https://github.com/etsy/AndroidStaggeredGrid  提供的瀑布流功能强大,可以自定义瀑布流列数。

      本篇博客,就讲解etsy的源码为主了。首先看效果图:

                                                                       

首先明确StaggeredGridView中几个变量的定义:

  1. private int mColumnCount;  /*程序默认瀑布流的列数,默认情况,通过资源文件中的integers.xml 中grid_column_count定义*/  
  2. private int mItemMargin;   /*程序默认瀑布流的的margin,通过layout文件activity_sgv.xml中的app:item_margin="8dp"定义*/  
  3. private int mColumnWidth;   /*程序瀑布流的列宽变量*/  
  4. private boolean mNeedSync;  
  5. private int mColumnCountPortrait = DEFAULT_COLUMNS_PORTRAIT; /*程序瀑布流竖屏列数*/  
  6. private int mColumnCountLandscape = DEFAULT_COLUMNS_LANDSCAPE;/*程序瀑布流横屏列数*/  

针对瀑布流,搞清楚如下几个问题,也算是吃透其中的原理了。


1.瀑布流的列数定义好了后,如何计算每列的宽度?
2.瀑布流的列数定义好了后,如何计算每列的高度?
3.瀑布流的HeaderView是如何添加的,其高度宽度如何确定?
4.瀑布流的FooterView是如何添加的,其高度宽度如何确定?
5.点击瀑布流的item时,高亮和默认背景的selector如何来实现?

一.瀑布流的列数定义好了后,如何计算每列的宽度?

     进入StaggeredGridActivity界面,瀑布流的UI效果已经出来了,主要看com.etsy.android.grid.StaggeredGridView的onMeasure方法,确定每一个view的尺度.

  1. @Override  
  2. protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {  
  3.     super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  4.     if (mColumnCount <= 0) {   
  5.         boolean isLandscape = isLandscape();  
  6.         mColumnCount = isLandscape ? mColumnCountLandscape : mColumnCountPortrait;  
  7.     }  
  8.     // our column width is the width of the listview   
  9.     // minus it's padding  
  10.     // minus the total items margin  
  11.     // divided by the number of columns  
  12.     mColumnWidth = calculateColumnWidth(getMeasuredWidth());  
变量mColumnCount是从资源文件integers.xml 中grid_column_count获取,默认是2,函数calculateColumnWidth用于计算列宽,其定义也比较简单,容易理解.
  1. private int calculateColumnWidth(final int gridWidth) {  
  2.     final int listPadding = getRowPaddingLeft() + getRowPaddingRight();  
  3.     return (gridWidth - listPadding - mItemMargin * (mColumnCount + 1)) / mColumnCount;  
  4. }  
即屏幕宽度 - listPadding - mItemMargin 除以 列数即item的宽度.此时此刻,列宽即可以得到。继续往下debug代码,由于是使用SampleAdapter,瀑布流中的每一个item均要调用getView方法,此方法跟所有的Adapter一样,要从layout文件中,导入用户自定义的布局文件。代码为:convertView = mLayoutInflater.inflate(R.layout.list_item_sample, parent, false);

资源文件list_item_sample.xml其定义如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:id="@+id/panel_content"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="horizontal" >  
  7.     <com.etsy.android.grid.util.DynamicHeightTextView  
  8.         android:id="@+id/txt_line1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:clickable="true"  
  12.         android:background="@drawable/list_item_selector"  
  13.         android:gravity="center" />  
  14.     <Button  
  15.         android:id="@+id/btn_go"  
  16.         android:layout_width="60dp"  
  17.         android:layout_height="60dp"  
  18.         android:layout_gravity="top|right"  
  19.         android:text="Go" />  
  20. </FrameLayout>  
       此处需要了解DynamicHeightTextView 的定义了。整个Adapter中,子item的尺度,均由DynamicHeightTextView 来确定。其类中的onMeasure如下:
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     if (mHeightRatio > 0.0) {  
  4.         // set the image views size  
  5.         int width = MeasureSpec.getSize(widthMeasureSpec);  
  6.         int height = (int) (width * mHeightRatio);  
  7.         setMeasuredDimension(width, height);  
  8.     }  
  9.     else {  
  10.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  11.     }  
  12. }  
 遍历mHeightRatio宽高比,从setHeightRatio中获取,经过层层代码跟踪,瀑布流中子item的高度已经剖析出来了。子view的宽高确定,首先要根据屏幕尺寸,确定宽度
然后根据SampleAdapter中的getRandomHeightRatio函数,确定高度,高度是宽度的1~1.5倍。

  1. private double getRandomHeightRatio() {  
  2.     return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width  

二.瀑布流的HeaderView和FooterView是如何添加的,其高度宽度如何确定?

    首先看效果图:

                                                                           

       从StaggeredGridActivity来看,就只有简单的一行代码,mGridView.addHeaderView(header),便可以给list增加head了。瀑布流的SampleAdapter如何跟headview结合在一起呢?

     在mGridView.setAdapter(mAdapter)时,调用ExtendableListView的setAdapter方法,ExtendableListView继承于AbsListView。ExtendableListView.java 的setAdapter方法如下:  

  1. @Override  
  2. public void setAdapter(final ListAdapter adapter) {  
  3.     if (mAdapter != null) {  
  4.         mAdapter.unregisterDataSetObserver(mObserver);  
  5.     }  
  6.     // use a wrapper list adapter if we have a header or footer  
  7.     if (mHeaderViewInfos.size() > 0 || mFooterViewInfos.size() > 0) {  
  8.         mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);  
  9.     }  
  10.     else {  
  11.         mAdapter = adapter;  
  12.     }  
mHeaderViewInfos或者mFooterViewInfos的size不为0时,构造一个HeaderViewListAdapter。其定义如下

  1. public class HeaderViewListAdapter implements WrapperListAdapter, Filterable  
从定义看以看出,该对象属于一个ListAdapter,既然是Adapter,当然逃不脱几个重要的函数了。getCount(),getItemViewType(),getView()。  
  1. public int getCount() {  
  2.     if (mAdapter != null) {  
  3.         return getFootersCount() + getHeadersCount() + mAdapter.getCount();  
  4.     } else {  
  5.         return getFootersCount() + getHeadersCount();  
  6.     }  
  7. }  
   getCount即adapter的item数量,当mAdapter!=null时,返回head和footer加上mAdapter.getCount.这样。head和footer也就与普通的瀑布流item一起,作为adapter的元素了。  
  1. public int getItemViewType(int position) {  
  2.     int numHeaders = getHeadersCount();  
  3.     if (mAdapter != null && position >= numHeaders) {  
  4.         int adjPosition = position - numHeaders;  
  5.         int adapterCount = mAdapter.getCount();  
  6.         if (adjPosition < adapterCount) {  
  7.             return mAdapter.getItemViewType(adjPosition);  
  8.         }  
  9.     }  
  10.     return AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER;  
  11. }  

     getItemViewType函数即更加参数position,来确定view type id,view是从getView函数中创建的。

该函数的意思是:head和footer的位置,返回AdapterView.ITEM_VIEW_TYPE_HEADER_OF_FOOTER,普通的瀑布流item,将返回mAdapter.getItemViewType(adjPosition)。接着重写getView函数。

  1. public View getView(int position, View convertView, ViewGroup parent) {  
  2.     // Header (negative positions will throw an ArrayIndexOutOfBoundsException)  
  3.     int numHeaders = getHeadersCount();  
  4.     if (position < numHeaders) {  
  5.         return mHeaderViewInfos.get(position).view;  
  6.     }  
  7.     // Adapter  
  8.     final int adjPosition = position - numHeaders;  
  9.     int adapterCount = 0;  
  10.     if (mAdapter != null) {  
  11.         adapterCount = mAdapter.getCount();  
  12.         if (adjPosition < adapterCount) {  
  13.             return mAdapter.getView(adjPosition, convertView, parent);  
  14.         }  
  15.     }  
  16.     // Footer (off-limits positions will throw an ArrayIndexOutOfBoundsException)  
  17.     return mFooterViewInfos.get(adjPosition - adapterCount).view;  
  18.  
     函数的意思理解也很容易,header位置,将返回mHeaderViewInfos.get(position).view;footer位置,返回mFooterViewInfos.get(adjPosition - adapterCount).view。其他的位置,也就是不规则GridView中的item view,返回mAdapter.getView(adjPosition, convertView, parent),mAdapter对象,将会调用到SampleAdapter.java中的getView方法了。

     至此,就明白了Header和footer是如何被添加到瀑布流界面了。接下来,就来确定head和footer的高度宽度问题了。瀑布流中,从UI效果来看,有三种类型的type view,一个是head,一个是StaggeredGridView,另外一个是footer了。计算子view的尺寸,当然要关注onMeasureChild函数了。StaggeredGridView.java中的onMeasureChild函数定义如下:

  1.    @Override  
  2.    protected void onMeasureChild(final View child, final LayoutParams layoutParams) {  
  3.        final int viewType = layoutParams.viewType;  
  4.        final int position = layoutParams.position;  
  5.   
  6.        if (viewType == ITEM_VIEW_TYPE_HEADER_OR_FOOTER ||  
  7.                viewType == ITEM_VIEW_TYPE_IGNORE) {  
  8.            // for headers and weird ignored views  
  9.            super.onMeasureChild(child, layoutParams);  
  10.        }

   可以看出,当viewType == ITEM_VIEW_TYPE_HEADER_OR_FOOTER时,调用父类ExtendableListView的onMeasureChild方法,计算head的尺度;当viewType!=ITEM_VIEW_TYPE_HEADER_OR_FOOTER时,走else流程,根据int childWidthSpec = MeasureSpec.makeMeasureSpec(mColumnWidth, MeasureSpec.EXACTLY) 来计算尺 寸。

三.点击瀑布流的item时,高亮和默认背景的selector如何来实现


   先上效果图:

    从github上下载的源代码,经过稍微的修改,便可以实现点击item高亮效果,还是在资源布局文件list_item_sample.xml中看出端倪:

  1. <com.etsy.android.grid.util.DynamicHeightTextView  
  2.     android:id="@+id/txt_line1"  
  3.     android:layout_width="wrap_content"  
  4.     android:layout_height="wrap_content"  
  5.     android:clickable="true"  
  6.     android:background="@drawable/list_item_selector"  
  7.     android:gravity="center" />  
代码:android:background="@drawable/list_item_selector"中,list_item_selector的定义如下:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <!-- shapes defined for Android 2.3 drawable issues -->  
  4.     <item android:state_pressed="true" >  
  5.         <shape android:shape="rectangle">  
  6.              <solid android:color="@color/list_item_pressed" />  
  7.         </shape>  
  8.     </item>  
  9.     <!-- default -->  
  10.     <item>  
  11.         <shape android:shape="rectangle">  
  12.              <solid android:color="@android:color/transparent" />  
  13.         </shape>  
  14.     </item>  
  15. </selector>  

   这个selector的意思是,默认情况下,使用全透明效果

  1. <solid android:color="@android:color/transparent" />  
点中状态时,呈现<solid android:color="@color/list_item_pressed" />的效果

   使用这种机制的原因,也很容易理解,在SampleAdapter中的getView函数中,代码:

  1. convertView.setBackgroundResource(mBackgroundColors.get(backgroundIndex));  

表示不同postion的item,显示不同的颜色,那么selector的定义,默认的情况时,使用全透明效果,UI上,就可以看到item的背景色,不会被selector的默认颜色遮挡。

    由于在https://github.com/etsy/AndroidStaggeredGrid中的项目工程,是在Android Studio中构建的,如果不习惯,可以使用eclipse中的,项目地址在:https://github.com/hero-peng/My-StaggeredGridView,需要的读者,请自行下载。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值