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


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

那么如果需要动态配置图片呢?我们不得不使用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,下次再分享其他的

原文地址:https://www.cnblogs.com/kunyashaw/p/4159976.html