Android TextView drawable,如何改变drawable和文本之间的填充?

65

我正在创建一个带有drawable的TextView,并将其放在GridLayout中。

我想将drawable放在TextView的中间; 我尝试使用setCompoundDrawablePadding(-75),但这仅更改了文本的位置。

当前代码:

    TextView secondItem = new TextView(this);
    GridLayout.LayoutParams second = new GridLayout.LayoutParams(row2, col1);
    second.width = halfOfScreenWidth;
    second.height = (int) (quarterScreenWidth * 1.5);
    secondItem.setLayoutParams(second);
    secondItem.setBackgroundResource(R.color.MenuSecond);
    secondItem.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, R.drawable.ic_action_new);
    secondItem.setText("Text");
    secondItem.setCompoundDrawablePadding(-180);
    secondItem.setGravity(Gravity.CENTER);
    secondItem.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
    gridLayout.addView(secondItem, second);

我该如何将文本和可绘制物设置到 TextView 的中间?

4个回答

143
您需要结合drawablePaddingpadding来得到所需的结果。

2
你会如何将它组合成不同的文本(例如不同的语言环境)? - orium

25

在 XML 中:

android:drawablePadding = paddingValue

或者

以编程方式:

TextView txt;

txt.setCompoundDrawablePadding(paddingValue)

android:drawablePadding 是给可绘制图标添加内边距最简单的方法,但是您不能像对待可绘制图标的 paddingRightpaddingLeft 一样单独地给出某一侧的内边距。它会在可绘制图标两侧添加内边距。


3
  <Button
            android:id="@+id/otherapps"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/btn_background"
            android:text="@string/other_apps"
            android:layout_weight="1"
            android:fontFamily="cursive"
            android:layout_marginBottom="10dp"
            android:drawableLeft="@drawable/ic_more"
            android:paddingLeft="8dp" //for drawable padding to the left
            android:textColor="@android:color/holo_red_light" />`enter code here`

1
你可以使用 layer-list。
之前:

enter image description here

创建用于形状的XML - shape_rectangle.xml :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="5dp">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="@color/my_color" />
        <size
            android:width="5dp"
            android:height="5dp" />
    </shape>
</item>
</layer-list>

之后:

enter image description here

在 XML 中,有类似 android:right 的东西。你还可以添加 topleftbottom。这样,您可以为 drawable 添加左右填充,而不改变 textView 的总高度大小。

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