Button往往在layout布局文件中添加,Button的背景色如果不做特殊修改,默认是灰色的,看起来很丑。那如何自定义Button的背景以及点击效果呢?
在Button的属性中background属性指定Button背景显示,如果指定一张图片即background="@drawable/btn_img"这样就能以该图片显示背景。如果要在点击Button的时候有点击效果,方法有两种:
方法一、在xml中配置:
<Button
android:id="@+id/permit_btn"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/btn_style"
android:textSize="16sp"
android:textColor="@color/red" />
而其中btn_style是在drawable文件夹下的一个xml文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/btn_default_pressed" />
<item android:state_focused="true" android:drawable="@drawable/btn_default_focused" />
<item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" />
<item android:drawable="@drawable/btn_default_disable" />
</selector>
一般我们定义三到四种状态就足够了,简单说明下:
android:state_pressed="true" 按下Button时显示对应的图片;
android:state_focused="true" 焦点在Button上时显示对应图片;
android:state_enabled="true" 可用状态即常见状态下显示对应的图片;
方法二、在代码中点击事件中处理:
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==MotionEvent.ACTION_DOWN){
v.setBackgroundResource(R.drawable.button_default_pressed);
}else if(event.getAction()==MotionEvent.ACTION_UP){
v.setBackgroundResource(R.drawable.button_default_nomal);
}
return false;
}
简单记录下,以备不时之需。