Android在代码中设置drawableLeft(Right/Top/Bottom)

根据业务的需要,要在代码中设置控件的drawableLeftdrawableRightdrawableTopdrawableBottom属性。

我们知道在xml中设置的方法为:

android:drawableLeft="@drawable/xxxxx"

但是在代码中并没有相关的setDrawableLeft等方法。怎么办呢?

别担心,api为我们提供了一个setCompoundDrawables(left,top,right,bottom);方法,供开发人员设置相应的边界图片。

操作方法十分简单,如下代码所示:

   // 使用代码设置drawableleft
   Drawable drawable = getResources().getDrawable(
         R.drawable.ic_qaa_top_icon);
   // 这一步必须要做,否则不会显示。
   drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
   Button.setCompoundDrawables(null, null, drawable, null);
发布了100 篇原创文章 · 获赞 45 · 访问量 64万+

猜你喜欢

转载自blog.csdn.net/wangzhongshun/article/details/99595386