欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发之ListView功能扩展,实现高性能的瀑布流布局讲解

程序员文章站 2023-10-12 20:12:15
listview的工作原理就非常巧妙,它使用recyclebin实现了非常出色的生产者和消费者的机制,移出屏幕的子view将会被回收,并进入到recyclebin中进行缓存,而新进入屏幕的子view...

listview的工作原理就非常巧妙,它使用recyclebin实现了非常出色的生产者和消费者的机制,移出屏幕的子view将会被回收,并进入到recyclebin中进行缓存,而新进入屏幕的子view则会优先从recyclebin当中获取缓存,这样的话不管我们有多少条数据需要显示,实际上屏幕上的子view其实也就来来回回那么几个。

那么,如果我们使用listview工作原理来实现瀑布流布局,效率问题、oom问题就都不复存在了,可以说是真正意义上实现了一个高性能的瀑布流布局。原理示意图如下所示:

Android开发之ListView功能扩展,实现高性能的瀑布流布局讲解

ok,工作原理确认了之后,接下来的工作就是动手实现了。由于瀑布流这个扩展对listview整体的改动非常大,我们没办法简单地使用继承来实现,所以只能先将listview的抽取出来,然后对其内部的逻辑进行修改来实现功能,那么我们第一步的工作就是要将listview的源码抽取出来。但是这个工作并不是那么简单的,因为仅仅listview这一个单独的类是不能够独立工作的,我们如果要抽取代码的话还需要将abslistview、adapterview等也一起抽取出来,然后还会报各种错误都需要一一解决,我当时也是折腾了很久才搞定的。所以这里我就不带着大家一步步对listview源码进行抽取了,而是直接将我抽取好的工程uilistviewtest上传到了csdn,大家只需要点击这里进行下载就可以了,今天我们所有的代码改动都是在这个工程的基础上进行的。

另外需要注意的是,为了简单起见,我没有抽取最新版本的listview代码,而是选择了android 2.3版本listview的源码,因为老版本的源码更为简洁,方便于我们理解核心的工作流程。

好的,那么现在将uilistviewtest项目导入到开发工具当中,然后运行程序,效果如下图所示:

Android开发之ListView功能扩展,实现高性能的瀑布流布局讲解

可以看到,这是一个非常普通的listview,每个listview的子view里面有一张图片,一段文字,还有一个按钮。文字的长度是随机生成的,因此每个子view的高度也各不相同。那么我们现在就来对listview进行扩展,让它拥有瀑布流展示的能力。

首先,我们打开abslistview这个类,在里面添加如下所示的几个全局变量:

protected int mcolumncount = 2;

protected arraylist[] mcolumnviews = new arraylist[mcolumncount];

protected map mposindexmap = new hashmap();

其中mcolumncount表示瀑布流布局一共有几列,这里我们先让它分为两列显示,后面随时可以对它进行修改。当然,如果想扩展性做的好的话,也可以使用自定义属性的方式在xml里面指定显示的列数,不过这个功能就不在我们本篇文章的讨论范围之内了。mcolumnviews创建了一个长度为mcolumncount的数组,数组中的每个元素都是一个泛型为view的arraylist,用于缓存对应列的子view。mposindexmap则是用于记录每一个位置的子view应当放置在哪一列当中。

接下来让我们回忆一下,listview最基本的填充方式分为向下填充和向上填充两种,分别对应的方法是filldown()和fillup()方法,而这两个方法的触发点都是在fillgap()方法当中的,fillgap()方法又是由trackmotionscroll()方法根据子元素的位置来进行调用的,这个方法只要手指在屏幕上滑动时就会不停进行计算,当有屏幕外的元素需要进入屏幕时,就会调用fillgap()方法来进行填充。那么,trackmotionscroll()方法也许就应该是我们开始着手修改的地方了。

这里我们最主要的就是修改对于子view进入屏幕判断的时机,因为原生的listview只有一列内容,而瀑布流布局将会有多列内容,所以这个时机的判断算法也就需要进行改动。那么我们先来看一下原先的判断逻辑,如下所示:

final int firsttop = getchildat(0).gettop();

final int lastbottom = getchildat(childcount - 1).getbottom();

final rect listpadding = mlistpadding;

final int spaceabove = listpadding.top - firsttop;

final int end = getheight() - listpadding.bottom;

final int spacebelow = lastbottom - end;

这里firsttop表示屏幕中第一个元素顶边的位置,lastbottom表示屏幕中最后一个元素底边的位置,然后spaceabove记录屏幕第一个元素顶边到listview上边缘的距离,spacebelow记录屏幕最后一个元素底边到listview下边缘的距离。最后使用手指在屏幕上移动的距离和spaceabove、spacebelow进行比较,来判断是否需要调用fillgap()方法,如下所示:

final int absincrementaldeltay = math.abs(incrementaldeltay);

if (spaceabove < absincrementaldeltay || spacebelow < absincrementaldeltay) {

fillgap(down);

}

了解了原先的工作原理之后,我们就可以来思考一下怎么将这个逻辑改成适配瀑布流布局的方式。比如说目前listview中有两列内容,那么获取屏幕中的第一个元素和最后一个元素其实意义是不大的,因为在有多列内容的情况下,我们需要找到的是最靠近屏幕上边缘和最靠近屏幕下边缘的元素,因此这里就需要写一个算法来去计算firsttop和lastbottom的值,这里我先把修改后的trackmotionscroll()方法贴出来,然后再慢慢解释:

boolean trackmotionscroll(int deltay, int incrementaldeltay) {

final int childcount = getchildcount();

if (childcount == 0) {

return true;

}

int firsttop = integer.min_value;

int lastbottom = integer.max_value;

int endbottom = integer.min_value;

for (int i = 0; i < mcolumnviews.length; i++) {

arraylist viewlist = mcolumnviews[i];

int size = viewlist.size();

if (size == 0) {

lastbottom = 0;

firsttop = 0;

endbottom = 0;

} else {

int top = viewlist.get(0).gettop();

int bottom = viewlist.get(size - 1).getbottom();

if (lastbottom > bottom) {

lastbottom = bottom;

}

if (endbottom < bottom) {

endbottom = bottom;

}

if (firsttop < top) {

firsttop = top;

}

}

}

final rect listpadding = mlistpadding;

final int spaceabove = listpadding.top - firsttop;

final int end = getheight() - listpadding.bottom;

final int spacebelow = lastbottom - end;

final int height = getheight() - getpaddingbottom() - getpaddingtop();

if (deltay < 0) {

deltay = math.max(-(height - 1), deltay);

} else {

deltay = math.min(height - 1, deltay);

}

if (incrementaldeltay < 0) {

incrementaldeltay = math.max(-(height - 1), incrementaldeltay);

} else {

incrementaldeltay = math.min(height - 1, incrementaldeltay);

}

final int firstposition = mfirstposition;

if (firstposition == 0 && firsttop >= listpadding.top && deltay >= 0) {

// don't need to move views down if the top of the first position

// is already visible

return true;

}

if (firstposition + childcount == mitemcount && endbottom <= end && deltay <= 0) {

// don't need to move views up if the bottom of the last position

// is already visible

return true;

}

final boolean down = incrementaldeltay < 0;

final boolean intouchmode = isintouchmode();

if (intouchmode) {

hideselector();

}

final int headerviewscount = getheaderviewscount();

final int footerviewsstart = mitemcount - getfooterviewscount();

int start = 0;

int count = 0;

if (down) {

final int top = listpadding.top - incrementaldeltay;

for (int i = 0; i < childcount; i++) {

final view child = getchildat(i);

if (child.getbottom() >= top) {

break;

} else {

count++;

int position = firstposition + i;

if (position >= headerviewscount && position < footerviewsstart) {

mrecycler.addscrapview(child);

int columnindex = (integer) child.gettag();

if (columnindex >= 0 && columnindex < mcolumncount) {

mcolumnviews[columnindex].remove(child);

}

}

}

}

} else {

final int bottom = getheight() - listpadding.bottom - incrementaldeltay;

for (int i = childcount - 1; i >= 0; i--) {

final view child = getchildat(i);

if (child.gettop() <= bottom) {

break;

} else {

start = i;

count++;

int position = firstposition + i;

if (position >= headerviewscount && position < footerviewsstart) {

mrecycler.addscrapview(child);

int columnindex = (integer) child.gettag();

if (columnindex >= 0 && columnindex < mcolumncount) {

mcolumnviews[columnindex].remove(child);

}

}

}

}

}

mmotionviewnewtop = mmotionvieworiginaltop + deltay;

mblocklayoutrequests = true;

if (count > 0) {

detachviewsfromparent(start, count);

}

tryoffsetchildrentopandbottom(incrementaldeltay);

if (down) {

mfirstposition += count;

}

invalidate();

final int absincrementaldeltay = math.abs(incrementaldeltay);

if (spaceabove < absincrementaldeltay || spacebelow < absincrementaldeltay) {

fillgap(down, down lastbottom : firsttop);

}

if (!intouchmode && mselectedposition != invalid_position) {

final int childindex = mselectedposition - mfirstposition;

if (childindex >= 0 && childindex < getchildcount()) {

positionselector(getchildat(childindex));

}

}

mblocklayoutrequests = false;

invokeonitemscrolllistener();

awakenscrollbars();

return false;

}

从第9行开始看,这里我们使用了一个循环,遍历瀑布流listview中的所有列,每次循环都去获取该列的第一个元素和最后一个元素,然后和firsttop及lastbottom做比较,以此找出所有列中最靠近屏幕上边缘的元素位置和最靠近屏幕下边缘的元素位置。注意这里除了firsttop和lastbottom之外,我们还计算了一个endbottom的值,这个值记录最底部的元素位置,用于在滑动时做边界检查的。

最重要的修改就是这些了,不过在其它一些地方还做了一些小的改动。观察第75行,这里是把被移出屏幕的子view添加到recyclebin当中,其实也就是说明这个view已经被回收了。那么还记得我们刚刚添加的全局变量mcolumnviews吗?它用于缓存每一列的子view,那么当有子view被回收的时候,mcolumnviews中也需要进行删除才可以。在第76行,先调用gettag()方法来获取该子view的所处于哪一列,然后调用remove()方法将它移出。第96行处的逻辑是完全相同的,只不过一个是向上移动,一个是向下移动,这里就不再赘述。

另外还有一点改动,就是我们在第115行调用fillgap()方法的时候添加了一个参数,原来的fillgap()方法只接收一个布尔型参数,用于判断向上还是向下滑动,然后在方法的内部自己获取第一个或最后一个元素的位置来获取偏移值。不过在瀑布流listview中,这个偏移值是需要通过循环进行计算的,而我们刚才在trackmotionscroll()方法中其实已经计算过了,因此直接将这个值通过参数进行传递会更加高效。

现在abslistview中需要改动的内容已经结束了,那么我们回到listview当中,首先修改fillgap()方法的参数:

@override

void fillgap(boolean down, int startoffset) {

final int count = getchildcount();

if (down) {

startoffset = count > 0 startoffset + mdividerheight : getlistpaddingtop();

filldown(mfirstposition + count, startoffset);

correcttoohigh(getchildcount());

} else {

startoffset = count > 0 startoffset - mdividerheight : getheight() - getlistpaddingbottom();

fillup(mfirstposition - 1, startoffset);

correcttoolow(getchildcount());

}

}

只是将原来的获取数值改成了直接使用参数传递过来的值,并没有什么太大的改动。接下来看一下filldown方法,原先的逻辑是在while循环中不断地填充子view,当新添加的子view的下边缘超出listview底部的时候就跳出循环,现在我们进行如下修改:

private view filldown(int pos, int nexttop) {

view selectedview = null;

int end = (getbottom() - gettop()) - mlistpadding.bottom;

while (nexttop < end && pos < mitemcount) {

boolean selected = pos == mselectedposition;

view child = makeandaddview(pos, nexttop, true, mlistpadding.left, selected);

int lowerbottom = integer.max_value;

for (int i = 0; i < mcolumnviews.length; i++) {

arraylist viewlist = mcolumnviews[i];

int size = viewlist.size();

if (size > 0) {

int bottom = viewlist.get(size - 1).getbottom();

if (bottom < lowerbottom) {

lowerbottom = bottom;

}

} else {

lowerbottom = 0;

break;

}

}

nexttop = lowerbottom + mdividerheight;

if (selected) {

selectedview = child;

}

pos++;

}

return selectedview;

}

可以看到,这里在makeandaddview之后并没有直接使用新增的view来获取它的bottom值,而是再次使用了一个循环来遍历瀑布流listview中的所有列,找出所有列中最靠下的那个子view的bottom值,如果这个值超出了listview的底部,那就跳出循环。这样的写法就可以保证只要在有子view的情况下,瀑布流listview中每一列的内容都是填满的,界面上不会有空白的地方出现。

接下来makeandaddview()方法并没有任何需要改动的地方,但是makeandaddview()方法中调用的setupchild()方法,我们就需要大刀阔斧地修改了。

大家应该还记得,setupchild()方法是用来具体设置子view在listview中显示的位置的,在这个过程中可能需要用到几个辅助方法,这里我们先提供好,如下所示:

private int[] getcolumntoappend(int pos) {

int indextoappend = -1;

int bottom = integer.max_value;

for (int i = 0; i < mcolumnviews.length; i++) {

int size = mcolumnviews[i].size();

if (size == 0) {

return new int[] { i, 0 };

}

view view = mcolumnviews[i].get(size - 1);

if (view.getbottom() < bottom) {

indextoappend = i;

bottom = view.getbottom();

}

}

return new int[] { indextoappend, bottom };

}

private int[] getcolumntoprepend(int pos) {

int indextoprepend = mposindexmap.get(pos);

int top = mcolumnviews[indextoprepend].get(0).gettop();

return new int[] { indextoprepend, top };

}

private void clearcolumnviews() {

for (int i = 0; i < mcolumnviews.length; i++) {

mcolumnviews[i].clear();

}

}

这三个方法全部都非常重要,我们来逐个看一下。getcolumntoappend()方法是用于判断当listview向下滑动时,新进入屏幕的子view应该添加到哪一列的。而判断的逻辑也很简单,其实就是遍历瀑布流listview的每一列,取每一列的最下面一个元素,然后再从中找出最靠上的那个元素所在的列,这就是新增子view应该添加到的位置。返回值是待添加位置列的下标和该列最底部子view的bottom值。原理示意图如下所示:

Android开发之ListView功能扩展,实现高性能的瀑布流布局讲解

然后来看一下getcolumntoprepend()方法。getcolumntoprepend()方法是用于判断当listview向上滑动时,新进入屏幕的子view应该添加到哪一列的。不过如果你认为这和getcolumntoappend()方法其实就是类似或者相反的过程,那你就大错特错了。因为向上滑动时,新进入屏幕的子view其实都是之前被移出屏幕后回收的,它们不需要关心每一列最高子view或最低子view的位置,而是只需要遵循一个原则,就是当它们第一次被添加到屏幕时所属于哪一列,那么向上滑动时它们仍然还属于哪一列,绝不能出现向上滑动导致元素换列的情况。而使用的算法也非常简单,就是根据当前子view的position值来从mposindexmap中获取该position值对应列的下标,mposindexmap的值在setupchild()方法当中填充,这个我们待会就会看到。返回值是待添加位置列的下标和该列最顶部子view的top值。

最后一个clearcolumnviews()方法就非常简单了,它就是负责把mcolumnviews缓存的所有子view全部清除掉。

所有辅助方法都提供好了,不过在进行setupchild之前我们还缺少一个非常重要的值,那就是列的宽度。普通的listview是不用考虑这一点的,因为列的宽度其实就是listview的宽度。但瀑布流listview则不一样了,列数不同,每列的宽度也会不一样,因此这个值我们需要提前进行计算。修改onmeasure()方法中的代码,如下所示:

protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {

......

setmeasureddimension(widthsize, heightsize);

mwidthmeasurespec = widthmeasurespec;

mcolumnwidth = widthsize / mcolumncount;

}

其实很简单,我们只不过在onmeasure()方法的最后一行添加了一句代码,就是使用当前listview的宽度除以列数,得到的就是每列的宽度了,这里将列的宽度赋值到mcolumnwidth这个全局变量上面。

现在准备工作都已经完成了,那么我们开始来修改setupchild()方法中的代码,如下所示:

private void setupchild(view child, int position, int y, boolean flowdown, int childrenleft,

boolean selected, boolean recycled) {

final boolean isselected = selected && shouldshowselector();

final boolean updatechildselected = isselected != child.isselected();

final int mode = mtouchmode;

final boolean ispressed = mode > touch_mode_down && mode < touch_mode_scroll &&

mmotionposition == position;

final boolean updatechildpressed = ispressed != child.ispressed();

final boolean needtomeasure = !recycled || updatechildselected || child.islayoutrequested();

abslistview.layoutparams p = (abslistview.layoutparams) child.getlayoutparams();

if (p == null) {

p = new abslistview.layoutparams(viewgroup.layoutparams.match_parent,

viewgroup.layoutparams.wrap_content, 0);

}

p.viewtype = madapter.getitemviewtype(position);

if ((recycled && !p.forceadd) || (p.recycledheaderfooter &&

p.viewtype == adapterview.item_view_type_header_or_footer)) {

attachviewtoparent(child, flowdown -1 : 0, p);

} else {

p.forceadd = false;

if (p.viewtype == adapterview.item_view_type_header_or_footer) {

p.recycledheaderfooter = true;

}

addviewinlayout(child, flowdown -1 : 0, p, true);

}

if (updatechildselected) {

child.setselected(isselected);

}

if (updatechildpressed) {

child.setpressed(ispressed);

}

if (needtomeasure) {

int childwidthspec = viewgroup.getchildmeasurespec(

measurespec.makemeasurespec(mcolumnwidth, measurespec.exactly), 0, p.width);

int lpheight = p.height;

int childheightspec;

if (lpheight > 0) {

childheightspec = measurespec.makemeasurespec(lpheight, measurespec.exactly);

} else {

childheightspec = measurespec.makemeasurespec(0, measurespec.unspecified);

}

child.measure(childwidthspec, childheightspec);

} else {

cleanuplayoutstate(child);

}

int w = child.getmeasuredwidth();

int h = child.getmeasuredheight();

if (needtomeasure) {

if (flowdown) {

int[] columninfo = getcolumntoappend(position);

int indextoappend = columninfo[0];

int childtop = columninfo[1];

int childbottom = childtop + h;

int childleft = indextoappend * w;

int childright = indextoappend * w + w;

child.layout(childleft, childtop, childright, childbottom);

child.settag(indextoappend);

mcolumnviews[indextoappend].add(child);

mposindexmap.put(position, indextoappend);

} else {

int[] columninfo = getcolumntoprepend(position);

int indextoappend = columninfo[0];

int childbottom = columninfo[1];

int childtop = childbottom - h;

int childleft = indextoappend * w;

int childright = indextoappend * w + w;

child.layout(childleft, childtop, childright, childbottom);

child.settag(indextoappend);

mcolumnviews[indextoappend].add(0, child);

}

} else {

int columnindex = mposindexmap.get(position);

if (flowdown) {

mcolumnviews[columnindex].add(child);

} else {

mcolumnviews[columnindex].add(0, child);

}

}

if (mcachingstarted && !child.isdrawingcacheenabled()) {

child.setdrawingcacheenabled(true);

}

}

第一个改动的地方是在第33行,计算childwidthspec的时候。普通listview由于子view的宽度和listview的宽度是一致的,因此可以在viewgroup.getchildmeasurespec()方法中直接传入mwidthmeasurespec,但是在瀑布流listview当中则需要再经过一个measurespec.makemeasurespec过程来计算每一列的widthmeasurespec,传入的参数就是我们刚才保存的全局变量mcolumnwidth。经过这一步修改之后,调用child.getmeasuredwidth()方法获取到的子view宽度就是列的宽度,而不是listview的宽度了。

接下来在第48行判断needtomeasure,如果是普通情况下的填充或者listview滚动,needtomeasure都是为true的,但如果是点击listview触发onitemclick事件这种场景,needtomeasure就会是false。针对这两种不同的场景处理的逻辑也是不一样的,我们先来看一下needtomeasure为true的情况。

在第49行判断,如果是向下滑动,则调用getcolumntoappend()方法来获取新增子view要添加到哪一列,并计算出子view左上右下的位置,最后调用child.layout()方法完成布局。如果是向上滑动,则调用getcolumntoprepend()方法来获取新增子view要添加到哪一列,同样计算出子view左上右下的位置,并调用child.layout()方法完成布局。另外,在设置完子view布局之后,我们还进行了几个额外的操作。child.settag()是给当前的子view打一个标签,记录这个子view是属于哪一列的,这样我们在trackmotionscroll()的时候就可以调用gettag()来获取到该值,mcolumnviews和mposindexmap中的值也都是在这里填充的。

接着看一下needtomeasure为false的情况,首先在第72行调用mposindexmap的get()方法获取该view所属于哪一列,接着判断是向下滑动还是向上滑动,如果是向下滑动,则将该view添加到mcolumnviews中所属列的末尾,如果是向上滑动,则向该view添加到mcolumnviews中所属列的顶部。这么做的原因是因为当needtomeasure为false的时候,所有listview中子元素的位置都不会变化,因而不需要调用child.layout()方法,但是listview仍然还会走一遍layoutchildren的过程,而layoutchildren算是一个完整布局的过程,所有的缓存值在这里都应该被清空,所以我们需要对mcolumnviews重新进行赋值。

那么说到layoutchildren过程中所有的缓存值应该清空,很明显我们还没有进行这一步,那么现在修改layoutchildren()方法中的代码,如下所示:

protected void layoutchildren() {

......

try {

super.layoutchildren();

clearcolumnviews();

......

} finally {

if (!blocklayoutrequests) {

mblocklayoutrequests = false;

}

}

}

很简单,由于刚才我们已经提供好辅助方法了,这里只需要在开始layoutchildren过程之前调用一下clearcolumnviews()方法就可以了。

最后还有一个细节需要注意,之前在定义mcolumnviews的时候,其实只是定义了一个长度为mcolumncount的arraylist数组而已,但数组中的每个元素目前还都是空的,因此我们还需要在listview开始工作之前对数组中的每个元素进行初始化才行。那么修改listview构造函数中的代码,如下所示:

public listview(context context, attributeset attrs, int defstyle) {

super(context, attrs, defstyle);

for (int i = 0; i < mcolumnviews.length; i++) {

mcolumnviews[i] = new arraylist();

}

......

}

这样基本上就算是把所有的工作都完成了。现在重新运行一下uilistviewtest项目,效果如下图所示:

Android开发之ListView功能扩展,实现高性能的瀑布流布局讲解

恩,效果还是相当不错的,说明我们对listview的功能扩展已经成功实现了。值得一题的是,这个功能扩展对于调用方而言是完全不透明的,也就是说在使用瀑布流listview的时候其实仍然在使用标准的listview用法,但是自动就变成了这种瀑布流的显示模式,而不用做任何特殊的代码适配,这种设计体验对于调用方来说是非常友好的。

另外我们这个瀑布流listview并不仅仅支持两列内容显示而已,而是可以轻松指定任意列数显示,比如将mcolumncount的值改成3,就可以变成三列显示了。不过三列显示有点挤,这里我把屏幕设置成横屏再来看一下效果:

Android开发之ListView功能扩展,实现高性能的瀑布流布局讲解

测试结果还是比较让人满意的。

最后还需要提醒大家一点,本篇文章中的例子仅供参考学习,是用于帮助大家理解源码和提升水平的,切误将本篇文章中的代码直接使用在正式项目当中,不管在功能性还是稳定性方面,例子中的代码都还达不到商用产品的标准。如果确实需要在项目实现瀑布流布局的效果,可以使用开源项目pinterestlikeadapterview的代码,或者使用android新推出的recyclerview控件,recyclerview中的staggeredgridlayoutmanager也是可以轻松实现瀑布流布局效果的。

好的,那么今天就到这里了,listview系列的内容也到此结束,相信大家通过这三篇文章的学习,对listview一定都有了更深一层的理解,使用listview时碰到了什么问题也可以更多从源码和工作原理的层次去考虑如何解决。感谢大家可以看到最后。