以编程方式在 TextView 中设置左可绘制 [英] Programmatically set left drawable in a TextView
问题描述
我在这里有一个 xml 格式的 textView.
I have a textView in xml here.
<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.
As you can see I set the DrawableLeft in xml.
我想在代码中更改可绘制对象.
I would like to change the drawable in code.
无论如何要这样做吗?或者在文本视图的代码中设置drawableLeft?
Is there anyway to go about doing this? Or setting the drawableLeft in code for the text view?
推荐答案
您可以使用 setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)
在不需要图片的地方设置 0
set 0 where you don't want images
左侧的 Drawable 示例:
Example for Drawable on the left:
TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
或者,您可以使用 setCompoundDrawablesRelativeWithIntrinsicBounds 以尊重 RTL/LTR 布局.
Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.
提示:当您知道任何 XML 属性但不知道如何在运行时使用它时.只需转到开发人员文档中对该属性的描述即可.如果运行时支持,您会在那里找到相关方法.即 对于 DrawableLeft
Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft
这篇关于以编程方式在 TextView 中设置左可绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!