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

2025-05-23 15:54:07
推荐回答(1个)
回答(1):

如何在代码中动态为TextView设置drawableRight | 浏览:42 |更新:2014-12-28 19:25 在写TextView的这个属性的drawableRight时,一般都是在xml里面写好的,但是我们有时候的需求是想在代码中动态的添加的效果,那么接下来我就来说说具体的方法。 工具/原料 android adt eclipse avd genymotion 方法/步骤 我们写在xml的时候,都是这么写的。那代码呢?我们发现TextView他有一个方法 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" 具体在代码中的用法是: Drawable drawable = getResources().getDrawable(R.drawable.spinner_checked); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界 titleTv.setCompoundDrawables(null, null, drawable, null);//画在右边 运行之后的效果 5 界面比较丑,勿喷,大家也还可以通过这个方法实现 public void setCompoundDrawablesWithIntrinsicBounds (Drawable left, Drawable top, Drawable right, Drawable bottom)