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

本文介绍了如何在Android开发中动态配置Button的上部、下部、左右的图片资源,并详细解释了如何确保图片保持原始大小的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


 

做安卓开发的朋友都知道,我们在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值