1 package com.dome; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.KeyEvent; 7 import android.view.View; 8 import android.view.WindowManager; 9 import android.view.inputmethod.InputMethodManager; 10 import android.widget.Button; 11 import android.widget.Toast; 12 13 /** 14 * 这是一个控制虚拟键盘的Dome 15 * 16 * @author wuxin 17 * 18 */ 19 public class KeyCodeDomeActivity extends Activity { 20 21 // 自定一个可以打开虚拟键盘的按钮 22 private Button button; 23 24 /** Called when the activity is first created. */ 25 @Override 26 public void onCreate(Bundle savedInstanceState) { 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.main); 29 30 // 获得它的资源 31 button = (Button) findViewById(R.id.button1); 32 33 // 设置它的监听事件 34 button.setOnClickListener(new View.OnClickListener() { 35 36 @Override 37 public void onClick(View v) { 38 // TODO Auto-generated method stub 39 40 // 获得控制键盘的类的对象 41 InputMethodManager imm = (InputMethodManager) KeyCodeDomeActivity.this 42 .getSystemService(INPUT_METHOD_SERVICE); 43 44 // 打开(自动控制的再次点击按钮就会消失的) 45 imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 46 } 47 }); 48 49 } 50 51 /** 52 * 当触发点击按钮事件后(仅限于虚拟键盘、返回键、Home键、菜单键....) 53 */ 54 @Override 55 public boolean onKeyDown(int keyCode, KeyEvent event) { 56 // TODO Auto-generated method stub 57 58 /* 59 * 判断是否点击的按键是返回键/注意添加权限:android.permission.BIND_INPUT_METHOD 60 */ 61 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { 62 63 Toast.makeText(KeyCodeDomeActivity.this, "我是返回键", 64 Toast.LENGTH_SHORT).show(); 65 66 return true;// 一定要设置为true否则回回退 67 68 } 69 70 /* 71 * 判断是否点击的按键是Home键/注意添加权限:android.permission.DISABLE_KEYGUARD 72 * 重点:一定要加上下面的onAttachedToWindow()方法 73 */ 74 if (KeyEvent.KEYCODE_HOME == keyCode) { 75 76 Toast.makeText(getApplicationContext(), "我是Home键", 77 Toast.LENGTH_SHORT).show(); 78 79 return true; 80 81 } 82 83 /* 84 * 判断是否点击的按键是menu键 85 */ 86 if(KeyEvent.KEYCODE_MENU == keyCode){ 87 88 Toast.makeText(getApplicationContext(), "我是Menu键", 89 Toast.LENGTH_SHORT).show(); 90 91 return true; 92 93 } 94 95 /* 96 * 判断是否点击的按键是搜索键 97 */ 98 if(KeyEvent.KEYCODE_SEARCH == keyCode){ 99 100 Toast.makeText(getApplicationContext(), "我是搜索键", 101 Toast.LENGTH_SHORT).show(); 102 103 return true; 104 105 } 106 107 108 return super.onKeyDown(keyCode, event); 109 } 110 111 /* 112 * (non-Javadoc) 113 * @see android.app.Activity#onAttachedToWindow() 114 */ 115 public void onAttachedToWindow() { 116 this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); 117 super.onAttachedToWindow(); 118 } 119 120 }