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

在写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.    运行之后的效果

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

5.    5

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

public voidsetCompoundDrawablesWithIntrinsicBounds (Drawable left,

Drawable top, Drawable right, Drawablebottom)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值