按键事件

package com.vanceinfo.KeyEvent;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class KeyEventActivity extends Activity
{
private Button button;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.ok_button);
button.setOnClickListener(listener);
}

OnClickListener listener = new OnClickListener()
{
@Override
public void onClick(View v)
{
DisplayToast("点击了OK!");
}
};

public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
DisplayToast("按下:中间键");
break;
case KeyEvent.KEYCODE_DPAD_UP:
DisplayToast("按下:向上键");
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
DisplayToast("按下:向下键");
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
DisplayToast("按下:左方向键");
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
DisplayToast("按下:有方向键");
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}

public boolean onKeyUp(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
DisplayToast("弹起:中间键");
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
DisplayToast("弹起:向下键");
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
DisplayToast("弹起:向左键");
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
DisplayToast("弹起:向右键");
break;
case KeyEvent.KEYCODE_DPAD_UP:
DisplayToast("弹起:向上键");
break;
}
return super.onKeyDown(keyCode, event);
}

public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
{
return super.onKeyMultiple(keyCode, repeatCount, event);
}

public boolean onTouchEvent(MotionEvent event)
{
int iAction = event.getAction();
if (iAction == MotionEvent.ACTION_CANCEL || iAction == MotionEvent.ACTION_DOWN
|| iAction == MotionEvent.ACTION_MOVE)
{
return false;
}
int x = (int) event.getX();
int y = (int) event.getY();
DisplayToast("触笔点击坐标:(" + Integer.toString(x) + "," + Integer.toString(y) + ")");
return super.onTouchEvent(event);
}

public void DisplayToast(String str)
{
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}

 

效果图

posted @ 2012-01-03 16:17  程序学习笔记  阅读(263)  评论(0编辑  收藏  举报