由于ListView只能实现数据纵向(垂直)方向的滚动效果,不能实现横向(水平)方向的滚动效果。因此,android官方更加推荐使用RecyclerView。
RecyclerView可以说是ListView的加强版,不仅可以实现和ListView同样的效果,还优化了ListView的不足之处,同时具有很好的扩展性(实现横向布局,网格布局,瀑布流布局)
RecyclerView是android新增的控件,为了能在所有android版本上使用,需要将它定义在support库中,即在项目的build.gradle中添加相应的依赖库。
实例:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.sky.recyclerviewdemo.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnVertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Vertical Layout"
android:textAllCaps="false"/>
<Button
android:id="@+id/btnHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Horizontal Layout"
android:textAllCaps="false"/>
<Button
android:id="@+id/btnGrid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Grid Layout"
android:textAllCaps="false"/>
<Button
android:id="@+id/btnStaggered"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Staggered Grid Layout"
android:textAllCaps="false"/>
</LinearLayout>
MainActivity.java
public