Android零基础入门第65节:RecyclerView分割线开发技巧

本文介绍了在RecyclerView中添加分割线的两种方法:通过背景设置显示间隔和自定义分割线。首先,通过给RecyclerView添加背景和item设置间隔来模拟分割线效果。其次,详细讲解如何利用RecyclerView的addItemDecoration方法结合自定义的ItemDecoration类来创建自定义分割线,以满足更复杂的界面需求。文章适合Android初学者,旨在帮助理解RecyclerView的灵活性和自定义性。
摘要由CSDN通过智能技术生成

   在上一期通过简单学习,已经领略到了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>

    其他地方的代码不变,重新运行程序,可以看到下图所示的分割线。

二、自定义分割线

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值