可以给Button控件同时设置图片以及文字,本文以给Button设置上图下文为例讲述一下怎么给控件设置图文信息以及怎么动态改变控件的图文信息:
在布局文件中可以通过下面的方式来给一个Button设置上图下文:
<Button
此处省去其他属性
android:drawableTop="@drawable/selector"
android:text="@string/home" />
但是怎么在java代码中动态改变这个Button的图片呢?
首先要得到要替换的图片:
如:
Drawable homepressed=getResources().getDrawable(R.drawable.setup_pressed);
再者要设置图片的边界,setBounds方法设置图片显示的位置,这个位置是相对Button而言的
如:
homepressed.setBounds(0, 0, homepressed.getMinimumWidth(), homepressed.getMinimumHeight());
第三,设置Button的四个方位的图片,下面的例子是设置Btton的Top方位的图片,其他方位设置为null
btn_home.setCompoundDrawables(null, homepressed, null, null);
这样就完成了Button的drawableLeft | Top |Right |Bottom的动态设置。
注:必须执行homepressed.setBounds(0, 0, homepressed.getMinimumWidth(), homepressed.getMinimumHeight());才能看出效果