做安卓开发的朋友都知道,我们在xml中可以通过这样来对button设置其上部或者(下、左、右)的图片资源:

 

4、android xml中drawableTop(drawableBoottom、drawableLeft、drawableRight)在java代码中的动态配置

那么如果需要动态配置图片呢?我们不得不使用java代码来进行操作:

Drawable drawable = null;

drawable=splash.contextTools.getResources().getDrawable(R.drawable.pepper);//得到drawable对象

drawable.setBounds(0, 0, 24,75);//设置drawable对象的宽度和高度
                              
new_button.setCompoundDrawables(null, null, drawable, null);//将drawable对象放在new_button的右侧(这里有个注意点,如果使用setCompundDrawables方法,一定要首先通过setBounds来配置一下图片资源)

new_button.setCompoundDrawablePadding(35); //设置drawable与new_button的间距

 

通过以上代码,就基本满足我们的使用需求了。

有些同学估计会问,如果我要保证图片原始大小怎么办呢?

setCompoundDrawablesWithIntrinsicBounds(null,null,drawable,null);//这个方法可以使用图片固有的宽度和高度

ok,下次再分享其他的

相关文章:

  • 2021-06-20
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
猜你喜欢
  • 2022-12-23
  • 2021-09-17
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
相关资源
相似解决方案