按键事件

1.代码:

Activity:

  1 package com.vanceinfo.KeyEvent;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.KeyEvent;
6 import android.view.MotionEvent;
7 import android.view.View;
8 import android.view.View.OnClickListener;
9 import android.widget.Button;
10 import android.widget.Toast;
11
12 public class KeyEventActivity extends Activity
13 {
14 private Button button;
15
16 @Override
17 public void onCreate(Bundle savedInstanceState)
18 {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.main);
21 button = (Button) findViewById(R.id.ok_button);
22 button.setOnClickListener(listener);
23 }
24
25 OnClickListener listener = new OnClickListener()
26 {
27 @Override
28 public void onClick(View v)
29 {
30 DisplayToast("点击了OK!");
31 }
32 };
33
34 public boolean onKeyDown(int keyCode, KeyEvent event)
35 {
36 switch (keyCode)
37 {
38 case KeyEvent.KEYCODE_DPAD_CENTER:
39 DisplayToast("按下:中间键");
40 break;
41 case KeyEvent.KEYCODE_DPAD_UP:
42 DisplayToast("按下:向上键");
43 break;
44 case KeyEvent.KEYCODE_DPAD_DOWN:
45 DisplayToast("按下:向下键");
46 break;
47 case KeyEvent.KEYCODE_DPAD_LEFT:
48 DisplayToast("按下:左方向键");
49 break;
50 case KeyEvent.KEYCODE_DPAD_RIGHT:
51 DisplayToast("按下:有方向键");
52 break;
53 default:
54 break;
55 }
56 return super.onKeyDown(keyCode, event);
57 }
58
59 public boolean onKeyUp(int keyCode, KeyEvent event)
60 {
61 switch (keyCode)
62 {
63 case KeyEvent.KEYCODE_DPAD_CENTER:
64 DisplayToast("弹起:中间键");
65 break;
66 case KeyEvent.KEYCODE_DPAD_DOWN:
67 DisplayToast("弹起:向下键");
68 break;
69 case KeyEvent.KEYCODE_DPAD_LEFT:
70 DisplayToast("弹起:向左键");
71 break;
72 case KeyEvent.KEYCODE_DPAD_RIGHT:
73 DisplayToast("弹起:向右键");
74 break;
75 case KeyEvent.KEYCODE_DPAD_UP:
76 DisplayToast("弹起:向上键");
77 break;
78 }
79 return super.onKeyDown(keyCode, event);
80 }
81
82 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
83 {
84 return super.onKeyMultiple(keyCode, repeatCount, event);
85 }
86
87 public boolean onTouchEvent(MotionEvent event)
88 {
89 int iAction = event.getAction();
90 if (iAction == MotionEvent.ACTION_CANCEL || iAction == MotionEvent.ACTION_DOWN
91 || iAction == MotionEvent.ACTION_MOVE)
92 {
93 return false;
94 }
95 int x = (int) event.getX();
96 int y = (int) event.getY();
97 DisplayToast("触笔点击坐标:(" + Integer.toString(x) + "," + Integer.toString(y) + ")");
98 return super.onTouchEvent(event);
99 }
100
101 public void DisplayToast(String str)
102 {
103 Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
104 }
105 }

效果图:



posted @ 2011-10-30 15:54  程序学习笔记  阅读(214)  评论(0编辑  收藏  举报