我有一个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?


当前回答

为什么不直接用背景色创建一个1dp高视图呢?然后它可以很容易地放在你想要的地方。

其他回答

<TextView
    android:id="@+id/textView3"
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="#72cdf4"
    android:text=" aa" />

只需添加这个TextView下面的文本,你想添加的边界

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

要改变这一点:

<TextView
    android:text="My text"
    android:background="@drawable/top_bottom_border"/>

我更喜欢“drawable/top_bottom_border.xml”中的这种方法:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:startColor="#000"
                android:centerColor="@android:color/transparent"
                android:centerX="0.01" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:angle="90"
                android:startColor="#000"
                android:centerColor="@android:color/transparent"
                android:centerX="0.01" />
        </shape>
    </item>
</layer-list>

这只是使边界,而不是一个矩形,将出现,如果你的背景有颜色。

写下下面的代码

<View
    android:layout_width="wrap_content"
    android:layout_height="2dip"
    android:layout_below="@+id/topics_text"
    android:layout_marginTop="7dp"
    android:layout_margin="10dp"
    android:background="#ffffff" />

您可以通过以下代码片段来实现这一点-

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--Minus (-) how much dp you gave in the stroke width from left right-->
    <item android:left="-10dp" android:right="-10dp">
        <shape
            android:shape="rectangle">
            <stroke android:width="10dp" android:color="@android:color/holo_red_dark" />
           <!--This is the main background -->
            <solid android:color="#FFDDDDDD" />
        </shape>
    </item>
</layer-list>

预览,