RecyclerView是Android 5.0推出的,是support-v7包中的新组件,它可以用来代替ListView和GridView,并且能够实现瀑布流的布局,更加高级并且更加灵活,提供更为高效的回收复用机制,同时实现管理与视图的解耦合。
RecyclerView可以显示大型数据集,可以通过回收有限数量的视图来有效滚动。 实例化ViewHolder视图时,可以定义单击监听器。 V7支持库中提供了RecyclerView,因此与API 7级及更高版本兼容。
Android Developer提供的示例代码请参考:
https://github.com/android/views-widgets-samples/tree/master/RecyclerView
以此示例代码学习介绍,将demo导入到Android studio中。
1.布局中添加
recycler_view_frag.xml中添加RecyclerView相关代码。
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
2.text_row_item.xml,为RecyclerView内的元素设定xml样式
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/list_item_height"
android:layout_marginLeft="@dimen/margin_medium"
android:layout_marginRight="@dimen/margin_medium"
android:gravity="center_vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/element_text"/>
</FrameLayout>
3.创建适配器继承自RecyclerView.Adapter
步骤:
1.创建适配器类CustomAdapter继承自RecyclerView.Adapter,泛型传入RecyclerView.ViewHolder类。
2.创建内部类即RecyclerView.ViewHolder类的子类,并初始化item的textView控件。
3.重写RecyclerView.Adapter类的相关方法如onCreateViewHolder,onBindViewHolder等。
public class CustomAdapter extends RecyclerView.Adapter