安卓如何设置不同颜色/宽度的上下边框?

4
我阅读了一些教程,但我只能实现在一侧或两侧使用相同颜色的边框。我试图创建一个样式来应用上边框与不同颜色和宽度的下边框。

因此,我希望顶部有一个2dp的蓝色边框,底部有一个3dp的红色边框。

这是我正在使用的用于应用顶部和底部边框的样式,但我不能更改顶部或底部的颜色。

<?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>

嗨,这段代码非常巧妙地使用了一些技巧,在某些边框上实现了不同的宽度(只需在彼此上面绘制几个形状)。干得好,我给你点赞 +1。 - Stoycho Andreev
1个回答

8

虽然有点脏,但它可以用 :).

您的图层列表可绘制项:

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

        </shape>
    </item>
    <!-- BOTTOM STROKE-->
    <item android:top="@dimen/top_stroke_width">
        <shape android:shape="rectangle">
            <solid android:color="@color/bottom_stroke_color" />
        </shape>
    </item>
    <!-- MAIN SHAPE -->
    <item android:top="@dimen/top_stroke_width" android:bottom="@dimen/bottom_stroke_width">
        <shape android:shape="rectangle">
            <solid android:color="@color/main" />
        </shape>
    </item>
</layer-list>

颜色定义:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="top_stroke_color">#0000FF</color>
    <color name="bottom_stroke_color">#FF0000</color>
    <color name="main">#00FF00</color>
</resources>

最后是dimens:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="top_stroke_width">10dp</dimen>
    <dimen name="bottom_stroke_width">20dp</dimen>
</resources>

在我的示例中,我有3个矩形,它们已经设置了正确的“边距”。每个矩形都比下方的矩形小,并覆盖它。根据我的解决方案,您可以为主形状的每个侧面创建4种不同的描边。

谢谢,它能正常工作。但是我最终选择了另一个解决方案。 - Ryan
你的解决方案是什么? - Christlin Panneer
我不同意你的看法。它非常干净! - Egemen Hamutçu

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