Android XML形状可绘制对象 - 如何绘制U形?

5

我需要创建一个XML形状可绘制对象,可以绘制没有上边框的矩形(“U形”)。我能够实现的是绘制一个矩形,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<solid android:color="@color/detailrow_bg_normal" />

<corners
    android:bottomLeftRadius="0dp"
    android:bottomRightRadius="0dp"
    android:radius="1dp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp" />

<padding
    android:bottom="2dip"
    android:left="1.5dip"
    android:right="1.5dip"
    android:top="8dip" />

<stroke
    android:width="1dip"
    android:color="@color/detailtable_border" />

但是,如果可能的话,我该如何定义没有顶部(或底部)线条的相同形状呢?

3个回答

11

您可以尝试使用layer-list。看看类似于这样的内容是否有效:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape android:shape="rectangle">
            <solid android:color="@color/detailtable_border" />
        </shape>
   </item>

   <item android:left="1.5dp" android:right="1.5dp" android:bottom="2dp">
      <shape android:shape="rectangle">
        <solid android:color="@color/detailrow_bg_normal" />
      </shape>
   </item>
</layer-list>

这将用边框颜色填充矩形,然后覆盖它以默认背景颜色,留下适当数量的右/左/下边框颜色显示。


2
太棒了:瞎猜也成功了 :)。很高兴知道它有所帮助。 - Femi

2

尝试这段代码,同时参考这个链接:::

我用这个方法得到了一个好的解决方案:

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- This is the line -->
    <item android:top="-1dp" android:right="-1dp" android:left="-1dp">
      <shape>
            <solid android:color="@android:color/transparent" />
            <stroke android:width="1dp" android:color="#ffffff" />
      </shape>
    </item>

</layer-list>

如果您需要透明颜色但仍带有描边颜色(在我的情况下,我只需要一条底线),那么这个方法很有效。如果您需要背景颜色,可以像上面的答案一样添加一个实心形状颜色。


0

你可以使用两个形状和一个LayerList来实现这一点,但我认为使用NinePatch可绘制对象既是更好的解决方案,也更容易使用。


考虑过这个,但需要对已实现的解决方案进行相当大的更改,我真的更喜欢使用XML格式的方式。 - Bachi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接