在上一期通过简单学习,已经领略到了RecyclerView的灵活性,当然都是一些最基础的用法,那么本期一起来学习RecyclerView的分割线使用。
相信有的比较细心的同学已经发现了,使用RecyclerView实现的List列表和ListView实现的列表有一些细微差距,item之间没有分割线,导致item之间相隔不明显,但在实际开发中有又往往需要。
由于RecyclerView并没有支持divider这样的属性,需要我们自己想办法来完成。主要有两种实现方式,接下来分别对其进行学习。
一、背景设置显示间隔
先给RecyclerView添加黑色背景,然后再给每个item添加白色背景并设置间隔1dp,这样自然就用背景空隙当做分割线了。
在上一期的基础上进行简单修改即可,修改后的recyclerview_layout.xml文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:background="#5000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
修改后的recyclerview_item.xml文件代码如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#fff"
android:layout_marginBottom="1dp"
android:padding="6dp" >
<ImageView
android:id="@+id/icon_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="6dp"
android:contentDescription="null"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/title_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/icon_img"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:text="Title"
android:textSize="16sp" />
<TextView
android:id="@+id/content_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/icon_img"
android:layout_alignParentRight="true"
android:layout_below="@id/title_tv"
android:layout_marginTop="5dp"
android:text="content"
android:textSize="12sp" />
</RelativeLayout>
其他地方的代码不变,重新运行程序,可以看到下图所示的分割线。