我有一个TextView,我想添加一个黑色边界沿其顶部和底部边界。我尝试添加android:drawableTop和android:drawableBottom到TextView,但这只会导致整个视图变成黑色。

<TextView
    android:background="@android:color/green"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawableTop="@android:color/black"
    android:drawableBottom="@android:color/black"
    android:text="la la la" />

有没有一种方法可以轻松地添加一个顶部和底部边界的视图(特别是TextView)在Android?


当前回答

你也可以使用9条路径来完成你的工作。创建它,使彩色像素的高度不相乘,但只有透明像素。

其他回答

添加文件到res/drawable

<?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:left="-2dp" android:right="-2dp">
            <shape android:shape="rectangle">
                <stroke
                    android:width="1dp"
                    android:color="#000000" />
            </shape>
        </item>
    </layer-list>

将此文件上的链接添加到后台属性

所以我想做一些稍微不同的事情:在底部唯一的边界,模拟一个ListView分隔符。我修改了Piet Delport的答案,得到了这个:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
   <item>
      <shape 
        android:shape="rectangle">
            <solid android:color="@color/background_trans_light" />    

        </shape>
   </item>

    <!-- this mess is what we have to do to get a bottom border only. -->
   <item android:top="-2dp"
         android:left="-2dp"
         android:right="-2dp"
         android:bottom="1px"> 
      <shape 
        android:shape="rectangle">    
            <stroke android:width="1dp" android:color="@color/background_trans_mid" />
            <solid android:color="@null" />
        </shape>
   </item>

</layer-list>

注意使用px而不是dp来获得恰好1像素的分隔线(一些手机DPIs会使1dp线消失)。

在android 2.2中,您可以执行以下操作。

创建一个xml可绘制对象,如/res/drawable/textlines.xml,并将其指定为TextView的背景属性。

<TextView
android:text="My text with lines above and below"
android:background="@drawable/textlines"
/>

xml / res / drawable - textlines。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape 
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FF000000" />
            <solid android:color="#FFDDDDDD" />

        </shape>
   </item>

   <item android:top="1dp" android:bottom="1dp"> 
      <shape 
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FFDDDDDD" />
            <solid android:color="#00000000" />
        </shape>
   </item>

</layer-list>

这样做的缺点是你必须指定一个不透明的背景颜色,因为透明度是行不通的。(至少我是这么认为的,但我错了)。在上面的例子中,你可以看到第一个形状#FFdddddd的纯色被复制到了第二个形状的描边颜色中。

你也可以将视图包装在FrameLayout中,然后设置框架的背景颜色和填充为你想要的;然而,textview,默认情况下有一个“透明”的背景,所以你需要改变textview的背景颜色。

就像@Nic Hubbard说的,有一个非常简单的方法来添加边界线。

<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="#000000" >
</View>

你可以改变高度和背景颜色为任何你想要的。