【问题标题】:How to add padding to drawable backgrounds?如何为可绘制背景添加填充?
【发布时间】:2018-07-17 02:03:12
【问题描述】:

我正在尝试为应用程序制作自定义 EditText 背景,但在正确格式化它时遇到了一些困难。我希望 EditText 字段带有下划线,所以我在这里有这段代码:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-3dp"
        android:right="-3dp"
        android:top="-3dp">
        <shape android:shape="rectangle">
            <stroke
                android:width="2dp"
                android:color="@color/colorAccent" />
            <solid
                android:color="@android:color/transparent" />
        </shape>
    </item>
</layer-list>

我遇到的问题是,背景似乎无法超出 View 对象的边界,因此如果我希望下划线位于 EditText 下方,我必须向 View 本身添加填充:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_default_dark"
    android:paddingBottom="3dp"
    android:paddingTop="3dp"/>

如果我想更改背景,我真的不喜欢必须更改几十个 EditText 小部件的想法,所以我想知道是否有办法在可绘制资源中添加填充?

【问题讨论】:

  • 我对 xml drawables 没有太多经验——Shape 标签中有 &lt;padding&gt; 标签。或者您可以创建一个style 并将其应用于每个EditText。这样你就拥有了所有的EditText,你只需要改变样式来影响所有的实例。
  • @Barns,非常感谢!甚至没想过要使用样式
  • 您是否尝试过使用Shape 标签中的 标签?

标签: android xml android-drawable


【解决方案1】:

我认为你无法通过形状来实现这一点。我用 Vector Drawable 解决了类似的问题。它们似乎可以在按钮下正确拉伸,并且可以用来代替形状可绘制对象。您可以在 svg (Adobe Illustrator) 中绘制这样的矢量。然后转换为 Android Vector。并在代码中进行调整。

示例:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="40dp"
    android:viewportWidth="200"
    android:viewportHeight="40">

    <path
        android:strokeColor="#FFFFFFFF"
        android:strokeWidth="1"
        android:strokeMiterLimit="10"
        android:pathData="M 16 40 L 184 40" />
</vector> 

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多