手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >android自定义按钮示例(重写imagebutton控件实现图片按钮)
android自定义按钮示例(重写imagebutton控件实现图片按钮)
摘要:由于项目这种类型的图片按钮比较多,所以重写了ImageButton类。复制代码代码如下:packageme.henji.widget;imp...

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

【android自定义按钮示例(重写imagebutton控件实现图片按钮)】相关文章:

android4.0 获取手机IP地址的问题

Android自定义控件之自定义属性

Android的ImageButton当显示Drawable图片时就不显示文字

Android中 自定义数据绑定适配器BaseAdapter的方法

Android-对自定义类型的list排序

Android开发之XML文件解析的使用

Android定制RadioButton样式三种实现方法

Android 控件(button)对齐方法实现详解

Android开发笔记之:在ImageView上绘制圆环的实现方法

android 自定义ScrollView实现背景图片伸缩的实现代码及思路

精品推荐
分类导航