1,key -- 實體按鍵,
現在手機物理按鍵越來越少
常見的有 KEYCODE_VOLUME_DOWN/UP KEYCODE_POWER KEYCODE_BACK KEYCODE_HOME KEYCODE_MENU
在一個activity 重載父類 的下面這三個方法來處理按鍵事件
public boolean onKeyDown(int keyCode, KeyEvent event)
public boolean onKeyUp(int keyCode, KeyEvent event)
public boolean onKeyLongPress(int keyCode, KeyEvent event)
很明顯,長按事件一般是放到 onKeyLongPress 函數中來處理的。
那具體是怎麼做的呢,下面請看步驟:
第一步,先在 onKeyDown 函數中判斷 event.getRepeatCount 的次數(實際上長按就是由一系列的onKeyDown事件觸發的)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
if (mCameraAppView.getVisibility() != View.VISIBLE) {
return false;
}
Log.v(TAG,"onKeyDown event.getRepeatCount() "+event.getRepeatCount());
if (event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return true;
}
return super.onKeyDown(keyCode, event);
}
如果一直按著不放,通過打 log 可以看到
onKeyDown event.getRepeatCount() 0
onKeyDown event.getRepeatCount() 1
onKeyDown event.getRepeatCount() 2
onKeyDown event.getRepeatCount() 3
onKeyDown event.getRepeatCount() 4
onKeyDown event.getRepeatCount() 5
onKeyDown event.getRepeatCount() 6
onKeyDown event.getRepeatCount() 7
onKeyDown event.getRepeatCount() 8
onKeyDown event.getRepeatCount() 9
onKeyDown event.getRepeatCount() 10
onKeyDown event.getRepeatCount() 11
onKeyDown event.getRepeatCount() 12
……
第二步,重載 onKeyLongPressed 函數,在這個函數中你可以添加你的處理
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
Log.v(TAG,"key long pressed keyCode = "+keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
Log.v(TAG,"KEYCODE_VOLUME_UP/DOWN long pressed");
lockLongPressKey = true;
onShutterButtonLongPressed();
return true;
default:
break;
}
return super.onKeyLongPress(keyCode, event);
}
第三步,如果在onKeyUp 函數中也處理了相同的按鍵的話,那麼需要對 onKeyLongPress 和 onKeyUp 中該按鍵的處理作互斥處理了
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
Log.v(TAG, "onKeyUp event.getRepeatCount() "+event.getRepeatCount());
if(lockLongPressKey){
lockLongPressKey = false;
return true;
}
if (event.getRepeatCount() == 0) {
Log.v(TAG, "prepare for onShutterButtonClick..");
if (mEnableRecordBtn && mReviewImage.getVisibility() != View.VISIBLE
&& mBgLearningMessageFrame.getVisibility() == View.GONE) {
if (mShutterButton != null && mShutterButton.isEnabled()) {
onShutterButtonFocus(false);
collapseCameraControls();//fulin@20121101@fix PD1218 B121027-224
onShutterButtonClick();
}
}
}
if (mCameraAppView.getVisibility() != View.VISIBLE) {
return false;
}
return true;
}
return super.onKeyUp(keyCode, event);
}
互斥處理的原因是,長按事件處理完後,松開按鍵後就會執行 onKeyUp 函數。而這兩處針對相同的按鍵想要實現的功能又不一樣
固在此添加一個 private boolean lockLongPressKey = false; 變量,在 onKeyLongPress 函數中處理過以後,在 onKeyUp中便不再處理。