您的位置:首页 > 编程语言

如何在代码中动态为TextView/Button设置drawableRight

2015-09-22 20:35 387 查看
在写TextView的这个属性的drawableRight时,一般都是在xml里面写好的,但是我们有时候的需求是想在代码中动态的添加的效果,那么接下来我就来说说具体的方法。

工具/原料

·        android adt eclipse

·        avd genymotion

方法/步骤

1.    <TextView

       android:id="@+id/Title"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:layout_weight="1"

       android:drawableRight="@drawable/check_down"

       android:gravity="center_vertical"

       android:textSize="24dip"

       android:maxLines="1"

       android:ellipsize="end"/>

我们写在xml的时候,都是这么写的。那代码呢?我们发现TextView他有一个方法

2.    public void  setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom);

这个方法呢,就是可以在Java代码动态的画 左上右下几个方向

类似于xml中的 android:drawableLeft="@drawable/icon"

android:drawableTop="@drawable/icon"

android:drawableRight="@drawable/icon"

android:drawableButtom="@drawable/icon"

3.    具体在代码中的用法是:

Drawable drawable =getResources().getDrawable(R.drawable.spinner_checked);

drawable.setBounds(0, 0,drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界

titleTv.setCompoundDrawables(null, null,drawable, null);//画在右边

4.    运行之后的效果



5.    5

界面比较丑,勿喷,大家也还可以通过这个方法实现

public voidsetCompoundDrawablesWithIntrinsicBounds (Drawable left,

Drawable top, Drawable right, Drawablebottom)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: