【问题标题】:Android TextView drawable, change padding between drawable and text?Android TextView 可绘制,更改可绘制和文本之间的填充?
【发布时间】:2013-10-22 04:01:34
【问题描述】:

我正在创建一个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);

如何将 text 和 drawable 设置到 TextView 的中间?

【问题讨论】:

    标签: android textview drawable padding


    【解决方案1】:

    您需要组合 drawablePaddingpadding 以获得所需的结果。

    【讨论】:

    • 如何将它组合成不同的文本(例如不同的语言环境)?
    【解决方案2】:

    在 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`
      

      【讨论】:

        【解决方案4】:

        您可以使用图层列表。

        之前:

        为形状创建 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>
        

        之后:

        在 xml 中,有类似 android:right 的东西。您也可以添加top,left,bottom。通过这种方式,您可以给出例如:在不调整 textView 总高度的情况下向 drawable 左右填充。

        【讨论】: