以编程方式在 TextView 中设置左可绘制对象 [英] Programmatically set left drawable in a TextView

查看:19
本文介绍了以编程方式在 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 属性但不知道如何在运行时使用它.只需转到开发人员文档中该属性的描述即可.如果在运行时支持,您将在那里找到 相关方法.即 For 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆