选项 1:形状可绘制
如果您想要在可以设置背景的布局或视图周围设置边框,这是最简单的选项。在如下所示的文件夹中创建一个 XML 文件drawable:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#8fff93" />
<stroke
android:width="1px"
android:color="#000" />
</shape>
solid如果您不想填充,可以删除。background="@drawable/your_shape_drawable"您的布局/视图上的设置。
选项 2:背景视图
这是我在RelativeLayout. 基本上,您在要提供边框的视图下方有一个黑色方块,然后为该视图提供一些填充(不是边距!),以便黑色方块在边缘显示出来。
显然,这只有在视图没有任何透明区域时才能正常工作。如果是这样,我建议您编写一个BorderView只绘制边框的自定义 - 它应该只有几十行代码。
<View
android:id="@+id/border"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/image"
android:layout_alignLeft="@+id/image"
android:layout_alignRight="@+id/image"
android:layout_alignTop="@+id/main_image"
android:background="#000" />
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_...
android:padding="1px"
android:src="@drawable/..." />
如果您想知道,它确实适用于adjustViewBounds=true. RelativeLayout但是,如果您想在RelativeLayout整个View. 在那种情况下,我会推荐Shapedrawable。
选项 3:9 补丁
最后一种选择是使用像这样的 9-patch 可绘制对象:

您可以在可以设置的任何视图上使用它android:background="@drawable/..."。是的,它确实需要是 6x6 - 我尝试了 5x5,但它不起作用。
这种方法的缺点是你不能很容易地改变颜色,但如果你想要花哨的边框(例如,只有顶部和底部的边框,就像这个问题一样),那么你可能无法用Shapedrawable来做,这不是很强大。
选项 4:额外视图
如果您只想要视图上方和下方的边框,我忘了提及这个非常简单的选项。您可以将视图垂直放置LinearLayout(如果还没有),然后View在其上方和下方添加空 s,如下所示:
<View android:background="#000" android:layout_width="match_parent" android:layout_height="1px"/>