以编程方式在 TextView 中设置左侧可绘制对象

2023-11-22

我这里有一个 xml 中的 textView 。

<TextView
        android:id="@+id/bookTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableLeft="@drawable/checkmark"
        android:gravity="center_vertical"
        android:textStyle="bold"
        android:textSize="24dip"
        android:maxLines="1"
        android:ellipsize="end"/>

正如你所看到的,我在 xml 中设置了 DrawableLeft。

我想更改代码中的可绘制对象。

有什么办法去做这件事吗?或者在代码中为文本视图设置drawableLeft?


您可以使用setCompoundDrawablesWithIntrinsicBounds(int 左, int 上, int 右, int 下)

在不需要图像的地方设置 0

左侧可绘制的示例:

TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

或者,您可以使用setCompoundDrawablesRelativeWithIntrinsicBounds尊重 RTL/LTR 布局。


提示:每当您知道任何 XML 属性但不知道如何在运行时使用它时。只需转到开发人员文档中对该属性的描述即可。在那里你会发现相关方法如果运行时支持。 IE。对于 DrawableLeft

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式在 TextView 中设置左侧可绘制对象 的相关文章

随机推荐