Android中有时需动态设置控件四周的drawble图片,这个时候就需要调用
setCompoundDrawables(left, top, right, bottom),
四个参数类型都是左边/顶部/右边/底部
Button继承TextView,所以可以采用相同的设置方法
方法一.XML方式
<Button android:id="@+id/btn" android:textColor="@color/shenghuise" android:drawableTop="@mipmap/ic_launcher" android:background="@color/white" android:textSize="17sp" android:layout_width="match_parent" android:layout_height="wrap_content" />
方法二.JAVA代码
Drawable dra;
Resources res = getResources();
dra= res.getDrawable(R.drawable.ic_launcher);
//调用setCompoundDrawables时,必须调用Drawable.setBounds()方法,否则图片不显示
dra.setBounds(0, 0,
dra.getMinimumWidth(),
dra.getMinimumHeight());
btn.setCompoundDrawables(null,
dra, null, null); //设置顶部图标
在Android开发中,动态地为控件如Button设置drawable图片可通过调用setCompoundDrawables方法,传入四个参数分别代表左右上下的图片。此方法同样适用于继承自TextView的Button。文中介绍了XML布局和JAVA代码两种实现方式,其中JAVA代码中需要注意使用Drawable.setBounds()来设定图片边界,否则可能无法显示。
9万+

被折叠的 条评论
为什么被折叠?



