完美解决方案:
在FramgentAvitvity中处理,重写onKeyDown函数,在 keyCode==KeyEvent.KEYCODE_BACK时判断当前是哪个Fragment,得到这个Fragment之后获得对应的WebView,操作webView.goBack()。
示例代码:
private long mExitTime;
public static final int TOAST_SHOW_EXIT=1000;
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (currentFragmentIndex==0) {
haswebviw((WebView)homeFragment.getView().findViewById(R.id.wb_home));
}else if(currentFragmentIndex==1){
haswebviw((WebView)myAppFragment.getView().findViewById(R.id.wb_myapp));
}else if(currentFragmentIndex==2){
haswebviw((WebView)messageCenterFragment.getView().findViewById(R.id.wb_message));
}
else{
exitBy2Click();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
public void haswebviw(WebView webView)
{
if(webView.canGoBack())
{
webView.goBack();
}
else{
exitBy2Click(); //这是退出方法
}
}
private void exitBy2Click() {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
Toast.makeText(this, "再点击返回一次退出", TOAST_SHOW_EXIT).show();
mExitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}