当前位置: 移动技术网 > IT编程>移动开发>Android > android自定义按钮示例(重写imagebutton控件实现图片按钮)

android自定义按钮示例(重写imagebutton控件实现图片按钮)

2019年07月24日  | 移动技术网IT编程  | 我要评论

超级中国6,莆田二手房出售,郑源所有歌曲

由于项目这种类型的图片按钮比较多,所以重写了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" />

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网