操纵可绘制对象

Manipulating drawable

我想制作一些 Drawable 作为 TextView 的背景。 TextView 的长度会有所不同,我希望 Drawable 随 TextView 一起扩展。我将Drawable设置为TextView的背景,但看起来很奇怪。

这是我的 TextView:

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:textColor="#ffffff"
    />

这是我的@drawable/background。它只是一个圆形矢量:

<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0"
    >

    <path
        android:fillColor="#80000000"
        android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z"
        />

</vector>

我希望可绘制对象随着 TextView 的长度扩展(它可能有多于一行)但保持边缘的形状(圆形)。我该怎么做?

您可以像这样在 TextView 上添加一些填充

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background"
android:padding="10dp"
android:textColor="#ffffff"
/>

按照以下方式创建可绘制的形状:

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

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

    <padding android:top="@dimen/margin_vsmall" android:bottom="@dimen/margin_vsmall" android:left="@dimen/margin_small" android:right="@dimen/margin_small" />

    <corners
        android:radius="@dimen/radius" />

</shape>

并应用到您的文本视图作为背景android:background="@drawable/yourshapedrawable

此处根据需要调整半径和填充。