您的位置:首页 > 移动开发 > Android开发

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

2012-12-28 11:37 549 查看
根据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);
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: