TextView 代码设置drawableLeft、drawableRight、drawableTop、drawableBottom

这个问题我遇到很多次了,用完之后就忘了,然后每次遇到到网上乱搜,这次把它记下来,对自己对别人也有帮助!

我想要用代码设置drawableRight,代码如下:

Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_new);  
textview.setCompoundDrawables(null, null, rightDrawable, null);  

运行后你会发现一点效果没有。为什么呢?解决办法如下:
API提示,setCompoundDrawables() 调用的时候,Drawable对象必须调用setBounds(int left, int top, int right, int bottom)方法
于是我们的全部代码如下:

Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_new);  
rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());  
textview.setCompoundDrawables(null, null, rightDrawable, null);  

如了说到这里吧,希望对大家有所帮助。

你可能感兴趣的:(代码,android,textview)