Android - 如何在ListView的背景上显示垂直线(并根据行高)?

Sar*_*oto 11 android listview background line drawable

如何在背景上显示垂直线,例如下图中以蓝色突出显示的线?

在此输入图像描述

在这个例子中,我有一个带有ImageView元素的ListView(和TextView,但它与行无关),我希望这些项目背景上的垂直线感觉它们与每个项目"连接".

另外,请注意垂直线不会填满所有背景.

垂直线在左侧,并且对于所有情况都不相等.有时它会填充所有行高(在大多数ListView行中),有时它只填充行高的一半(在ListView的最后一项和ListView之外,在顶部,我们可以看到大的ImageView与星形图标).

更新

我尝试了Hellboy提出的建议,它几乎完美无缺.我为我的案例修改了建议的代码:

<RelativeLayout 
android:layout_width="40dp"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginLeft="15dp">

<View
    android:layout_width="4dp"
    android:layout_height="match_parent"
    android:background="#3399CC"
    android:gravity="center"
    android:layout_centerHorizontal="true"/>

<ImageView
    android:id="@+id/user_image"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:gravity="center"
    android:background="@android:color/holo_blue_light" >
</ImageView> 
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

RelativeLayout的宽度="40dp"(与我正在使用的原始ImageView相同),height ="match_parent(与他说的相同),gravity ="center"(让它们在行高的中心) )和layout_marginLeft ="15dp"(让空格到左边距).在ImageView中,我添加了marginTop ="10dp"和marginBottom ="10dp",并且随之显示蓝色垂直线.但我有其他同一行中的元素,所以我有一个父布局(一个线性布局).我的父布局是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center"
    android:id="@+id/linearlayoutservicerow">
Run Code Online (Sandbox Code Playgroud)

因此,上面的这个父布局具有描述的RelativeLayout和其他行元素的其他LinearLayout.但是代码会导致图像变平.为什么会这样?!似乎RelativeLayout将其高度视为ImageView高度(40dp),并考虑其marginTop和marginBottom,并且此时图像被展平.

等待这个问题的更多答案.我会尝试另一种选择.

Hel*_*boy 5

您可以使用以下内容替换ImageView:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="4dp"
        android:layout_height="match_parent"
        android:background="@color/navy_blue"
        android:layout_centerHorizontal="true"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/image"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

当然,在你的第一个和最后一个元素中你需要操纵它的高度View并将它对齐到顶部或底部


din*_*rma 3

您可以使用透明的 9 块图像作为列表视图的背景。

要创建九补丁图像,请按照以下步骤操作: http ://developer.android.com/tools/help/draw9patch.html