在Activity中嵌入Fragment中的webview,点击onKeyDown的事件截取。
在Activity中重写OnkeyDown事件:
功能描述是当定位处于第二个fragment时,不执行双击退出应用程序,而是执行子fragment中的onKeyDown事件
private long firstime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (index == 1) {
Fragment fragment = mFragments.get(1);
((DynamicFragment) fragment).onKeyDownChild(keyCode, event);
return true;
} else {
if (keyCode == KeyEvent.KEYCODE_BACK) {
long secondtime = System.currentTimeMillis();
if (secondtime - firstime > 3000) {
Toast.makeText(this, getString(R.string.again_exit), Toast.LENGTH_SHORT).show();
firstime = System.currentTimeMillis();
} else {
ActivityManager.getInstance().finishAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
写Fragment中的onKeyDownChild事件:
功能描述是拦截物理按键onKeyDown事件,执行此处,先判断是否可回退,如果不可回退,双击两次物理按键为退出应用程序;判断可回退,则先回退。
private long firstime = 0;
public void onKeyDownChild(int keyCode, KeyEvent event) {
if (webview.canGoBack()) {
webview.goBack();
if (webview.canGoBack()) {
actionbar.setLeftStatus(true);
bar.setVisibility(View.VISIBLE);
iv_send.setVisibility(View.GONE);
} else {
iv_send.setVisibility(View.VISIBLE);
actionbar.setLeftStatus(false);
bar.setVisibility(View.GONE);
((MainActivity) getActivity()).setBottom(true);
}
} else {
actionbar.setLeftStatus(false);
bar.setVisibility(View.GONE);
iv_send.setVisibility(View.VISIBLE);
if (keyCode == KeyEvent.KEYCODE_BACK) {
long secondtime = System.currentTimeMillis();
if (secondtime - firstime > 3000) {
Util.showSingleToast(getString(R.string.again_exit));
firstime = System.currentTimeMillis();
} else {
ActivityManager.getInstance().finishAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
}
}
|