android view重写onTouchEvent事件更换背景(android 动态设置背景图 )

根据MotionEvent event.getAction()可以动态更换View样式

event.getAction()==MotionEvent.ACTION_UP||event.getAction()==MotionEvent.ACTION_CANCEL //ACTION_MOVE事件以后松手后走不到ACTION_UP而是ACTION_CANCEL

package cn.qiluzhixiao.Activity;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.Toast;

public class MyButton extends Button {
	private Drawable img_on, img_off;
	public MyButton(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	public MyButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public MyButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		Resources res = getResources();
		img_on = res.getDrawable(R.drawable.android_spinner_right_pressed);
		img_off = res.getDrawable(R.drawable.android_spinner_right);
		//调用setCompoundDrawables时,必须调用Drawable.setBounds()方法,否则图片不显示
		img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
		img_on.setBounds(0, 0, img_on.getMinimumWidth(), img_on.getMinimumHeight());
	}
	
	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()) {
		case 0:
			
			break;

		default:
			break;
		}
		if(event.getAction()==MotionEvent.ACTION_UP||event.getAction()==MotionEvent.ACTION_CANCEL)
		{
			this.setCompoundDrawables(null, null, img_off, null); //设置右图标
		}
		if(event.getAction()==MotionEvent.ACTION_DOWN)
		{
			this.setCompoundDrawables(null, null, img_on, null); //设置右图标
		}
		return super.onTouchEvent(event);
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daodaowolf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值