一个RecyclerView的案例和解析
之前介绍了ListView的使用,如果在使用ListView的时候不使用一些技巧,listView的性能是不好的,而且它的扩展性也不好,只能支持纵向滚动效果,如果想实现横向的滚动效果,ListView是无法实现的。因此Android 提供了一个更强大的滚动控件RecyclerView, 它不仅能实现与ListView相同的效果,同时也补充了ListView的不足之处。
开始介绍RecyclerView的使用
RecyclerView是定义在support库中的新增的控件,所以使用的时候需要在项目的build.gradle文件中dependencies闭包中添加依赖
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1', 添加完后,需要点击Sync now 进行同步。
如下:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
testCompile 'junit:junit:4.12'
}
API代码引入后,就可以正常使用,RecyclerView的实现略微复杂,但是代码清晰容易理解。
UI布局
Activity_main.xml 中使用RecyclerView标签的时候要添加完整包名,因为它并不在内置的sdk系统中,然后设定id, 并且配置高度和宽度都是match_parent,这样RecyclerView将充满整个布局空间。
Fruit_item.xml 中实现了RecyclerView子项的布局设计,如下代码所示: