android监听键盘事件KeyEvent

在Activity的onKeyDown中可以监听到用户的键盘事件

代码很简单, 如下所示

package com.example.testkeyevent;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView tv_keycode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		getViews();
		
	}

	/**
	 * 
	 */
	private void getViews() {
		tv_keycode = (TextView) findViewById(R.id.tv_keycode);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean onKeyDown = super.onKeyDown(keyCode, event);
		tv_keycode.setText("des = "+KeyEvent.keyCodeToString(keyCode)+" : code = "+keyCode);
		System.out.println(event);
//		System.out.println(event.getAction());
//		System.out.println(event.getCharacters());
//		System.out.println(event.getDeviceId());
//		System.out.println(event.getDisplayLabel());
//		System.out.println(event.getDownTime());
//		System.out.println(event.getEventTime());
//		System.out.println(event.getFlags());
//		System.out.println(event.getKeyCode());
//		
//		System.out.println(KeyEvent.keyCodeToString(keyCode));
		
		return onKeyDown;
	}

}


你可能感兴趣的:(android监听键盘事件KeyEvent)