安卓在代码中给button添加和设置图片

首先获得Drawable对象:

Button button = (Button) findViewById(R.id.button1);
//获得Drawable对象
Drawable drawable = getDrawable(R.drawable.ic_launcher);
然后加入setCompoundDrawables(left, top, right, bottom)这个方法,left, top, right, bottom代表图片在button的位置,比如只在左边:

button.setCompoundDrawables(drawable,null, null, null);
其他为null。当然,这样的自由度还不够。可在button.setCompoundDrawables(drawable,null, null, null);之前插入drawable.setBounds(left, top, right, bottom);

其代表的意思是图片离button的距离。示例如下,图片在button左边20个单位处

Button button = (Button) findViewById(R.id.button1);
Drawable drawable = getDrawable(R.drawable.ic_launcher);
drawable.setBounds(20, 0, 0, 0);
button.setCompoundDrawables(drawable,null, null, null);







你可能感兴趣的:(安卓控件小问题)