android代码设置drawable,Android:Textview 通过代码设置 Drawable

效果图

8d05eeb78875?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

drawableright.jpg

这里价格右边的图片,就是需要不断改变的

这样的布局,相信大家都很熟悉吧

android:id="@+id/price_tv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:drawableEnd="@drawable/sx_0"

android:drawablePadding="10dp"

android:gravity="center"

android:text="价格"

android:textColor="@color/goods_list_top_no_select" />

android:drawableEnd 这种写法很简便,就是在textview的右边加一张图片,

但是有的时候,我们需要在代码中动态的设置android:drawableEnd,这种情况又该肿么办呢?

解决方案

/**

*

* @param left 图片在左边

* @param top 图片在上边

* @param right 图片在右边

* @param bottom 图片在下边

*/

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

使用 TextView 直接调用 setCompoundDrawables() 就可以实现添加 drawable

完整代码

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

drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());

priceTv.setCompoundDrawables(null, null, drawable, null);