展会信息港展会大全

Android ListView那些事
来源:互联网   发布日期:2015-12-04 16:23:48   浏览:946次  

导读:ListView是我们在开发Android程序时用得比较多的一种widget,通常用来展示多条数据,这里,我对ListView的一些功能点作一个简单介绍。1. Cache color h...

ListView是我们在开发Android程序时用得比较多的一种widget,通常用来展示多条数据,这里,我对ListView的一些功能点作一个简单介绍。

1. Cache color hint

默认情况下,Android中的View的背景都是透明的,这是一个合理的设计,但是,当渲染到屏幕上时,这会引入许多的计算,因为所有的child的背景是透明的,这就意味着当ListView绘制它的child时,会导致child与window的背景色相混合,当ListView上下滑动或Fling时,性能就会下降。当ListView上下滑动或者是Fling时,为了避免这种情况发生或提高渲染速度,ListView引入了"scrolling cache"机制。这个机制简单地说来就是ListView把可见的child绘制在一个bitmap上面(系统将每一个child拷贝到由cache

color hint填充的bitmap上面),然后再直接把这个bitmap绘制到屏幕上,由于这个bitmap是不透明的,所以就不会有混合计算,这样就提高了绘制的效率。

但是,由于系统默认的cache color hint的颜色是#191919,当你滑动ListView时,你就会看到一个黑色的背景。

出现这种情况肯定是不正确的,那么怎么解决呢?

最简单的方法是将cache color hint设置为透明。

android:cacheColorHint="#00000000" 或 setCacheColorHint(Color.TRANSPARENT)

以下是官方文档的原文:

As mentioned before, ListView has a transparent/translucent background by default, and so all default widgets in the Android UI toolkit. This implies that when ListView redraws its children, it has to blend the children with the window's background. Once again,

this requires costly readbacks from memory that are particularly painful during a scroll or a fling when drawing happens dozen of times per second.

To improve drawing performance during scrolling operations, the Android framework reuses the cache color hint. When this hint is set, the framework copies each child of the list in a Bitmap filled with the hint value (assuming that another optimization, called

scrolling cache, is not turned off). ListView then blits these bitmaps directly on screen and because these bitmaps are known to be opaque, no blending is required. Also, since the default cache color hint is #191919, you get a dark background behind each

item during a scroll.

To fix this issue, all you have to do is either disable the cache color hint optimization, if you use a non-solid color background, or set the hint to the appropriate solid color value. You can do this from code (see setCacheColorHint(int)) or preferably from

XML, by using the android:cacheColorHint attribute. To disable the optimization, simply use the transparent color #00000000. The following screenshot shows a list with android:cacheColorHint="#00000000" set in the XML layout file.

2. Divider

通过android:divider XML属性来指定。

Divider可以颜色或者Drawable,当绘制内容时,ListView会自动地计算出divider的位置。由于divider接收一个drawable,它可以是ColorDrawable,也可以是BitmapDrawable,但是,由于ColorDrawable,它是没有高度的,所以Drawable#getIntrinsicHeight()方法返回-1,因此,为了避免这个问题, 我们可以通过android:dividerHeight属性来设计其高度。

3. ListView绘制顺序

对于ListView的绘制顺序,我们很有必要了解一下。先看一下下面的图片。

\

从上面的图片可以看出,Android首先绘制背景和Dividers,然后再绘制其selector,最后,绘制所有的item在最上面。

由于通过情况下,listview的item的背景是透明的,所以,当用户按下一个item时,黄色的selectZ

赞助本站

人工智能实验室

相关热词: android开发 教程

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港