Android 捕获组合键
Android组合键
http://www.eoeandroid.com/thread-162824-1-1.html
Sample Code:
//Android监听组合键
package com.fuwei.action;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
onClickView();
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
Toast.makeText(this, "Home", 1);
super.onRestart();
}
public void onClickView() {
TextView textView = (TextView) findViewById(R.id.linear);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundColor(0xFF00FF00);
}
});
}
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// // TODO Auto-generated method stub
// if(!event.isAltPressed()&&keyCode == KeyEvent.KEYCODE_A){
// Toast.makeText(Main.this, "ALT + A", 0).show();
// }
// return super.onKeyDown(keyCode, event);
// }
// @Override
// public boolean dispatchKeyEvent(KeyEvent event) {
// // TODO Auto-generated method stub
// //Alt Shift System 等键可以用is....判断是否为按下状态
// if(event.isAltPressed()&&event.getKeyCode() == KeyEvent.KEYCODE_A){
// Toast.makeText(Main.this, "ALT + A", 0).show();
// }
// return super.dispatchKeyEvent(event);
// }
boolean aIsDown = false;
boolean qIsDown = false;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// TODO Auto-generated method stub
// 判断普通按键
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_A
&& event.getAction() == KeyEvent.ACTION_DOWN) {
aIsDown = true;
} else if (keyCode == KeyEvent.KEYCODE_Q
&& event.getAction() == KeyEvent.ACTION_DOWN) {
qIsDown = true;
}else if((keyCode == KeyEvent.KEYCODE_Q && !aIsDown)||(keyCode == KeyEvent.KEYCODE_A && !qIsDown)){
aIsDown = false;
qIsDown = false;
}else if (aIsDown
&& qIsDown
&& (keyCode == KeyEvent.KEYCODE_Q || keyCode == KeyEvent.KEYCODE_A)
&& event.getAction() == KeyEvent.ACTION_UP) {
Toast.makeText(Main.this, "Q + A", 0).show();
aIsDown = false;
qIsDown = false;
}else{
aIsDown = false;
qIsDown = false;
}
return super.dispatchKeyEvent(event);
}
}