当前的Fragment实现监听接口:
implements OnKeyDownListenter
public interface OnKeyDownListenter {
/**
* 键盘按钮按键处理
*
* @param keyCode
* @param event
* @return true 已执行处理 false 未执行
*/
public boolean onKeyDown(int keyCode, KeyEvent event);
}
当前Fragment:
private void init() {
((getActivity())).setOnAcitivityCallback(this);
}
ondestory时候
homePageActivity.removeCallbackListener();
当前Fragment:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//要做的事情
XXXX
return true;
}
return false;
}
Activity里面:
private OnKeyDownListenter mDoneCallback = null;// Fragmet操作 回调对象
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mDoneCallback != null && mDoneCallback.onKeyDown(keyCode, event)) {
return true;
}
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
mExitTime = System.currentTimeMillis();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void removeCallbackListener() {
this.mDoneCallback = null;
}