android自定义按钮示例(重写imagebutton控件实现图片按钮)
由于项目这种类型的图片按钮比较多,所以重写了imagebutton类。
package me.henji.widget;
import android.content.context;
import android.graphics.colormatrix;
import android.graphics.colormatrixcolorfilter;
import android.util.attributeset;
import android.view.motionevent;
import android.view.view;
import android.view.view.onfocuschangelistener;
import android.view.view.ontouchlistener;
import android.widget.imagebutton;
/**
* 自定义图片按钮(imagebutton),按下颜色改变
* @author leo
* @created 2013-3-15
*/
public class cmbutton extends imagebutton implements ontouchlistener, onfocuschangelistener {
public cmbutton(context context) {
super(context);
this.setontouchlistener(this);
this.setonfocuschangelistener(this);
}
public cmbutton(context context, attributeset attrs) {
this(context, attrs, android.r.attr.imagebuttonstyle);
this.setontouchlistener(this);
this.setonfocuschangelistener(this);
}
public cmbutton(context context, attributeset attrs, int defstyle) {
super(context, attrs, defstyle);
setfocusable(true);
this.setontouchlistener(this);
this.setonfocuschangelistener(this);
}
@override
public void onfocuschange(view v, boolean hasfocus) {
// 灰色效果
colormatrix cm = new colormatrix();
cm.setsaturation(0);
if (hasfocus) {
((imagebutton) v).getdrawable().setcolorfilter(new colormatrixcolorfilter(cm));
} else {
((imagebutton) v).getdrawable().clearcolorfilter();
}
}
@override
public boolean ontouch(view v, motionevent event) {
// 灰色效果
colormatrix cm = new colormatrix();
cm.setsaturation(0);
if (event.getaction() == motionevent.action_down) {
((imagebutton) v).getdrawable().setcolorfilter(new colormatrixcolorfilter(cm));
} else if (event.getaction() == motionevent.action_up) {
((imagebutton) v).getdrawable().clearcolorfilter();
}
return false;
}
}
布局文件
<me.henji.widget.cmbutton
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:src="@drawable/button_login"
android:text="@string/login_login" />