键盘按下和抬起事件(onKeyDown和onKeyUp)

时间:2024-03-08 11:55:24
package com.luohaibo.testdemo08;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //按键按下事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        //输出按键代码
        Log.d("onkeyDown:KeyCode", String.valueOf(keyCode));
        //输入按键的重复次数
        Log.d("onKeyCodeDown:RepeatCount", String.valueOf(event.getRepeatCount()));
        //如果重复次数到了200(8秒左右),显示提示信息
        if (event.getRepeatCount() == 200) {
            Toast.makeText(this, "已经按了一会儿,累了吧,该松开了", Toast.LENGTH_LONG).show();
            
        }
    //如果按下的是“菜单”按钮,输出日志信息
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            Log.d("onKeyDown", "MenuKey Down");
            
        }
        
        
        return super.onKeyDown(keyCode, event);
        
        
    }
    //按键抬起事件
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            Log.d("onKeyUp", "MenuKey Up");
            
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}