這項工作對我來說
public class MyWebView extends Fragment {
private WebView mWebView;
private View rootView;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:{
webViewGoBack();
}break;
}
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.testwebview, null);
mWebView = (WebView)rootView.findViewById(R.id.webview);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.loadUrl("myurl...");
mWebView.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& mWebView.canGoBack()) {
handler.sendEmptyMessage(1);
return true;
}
return false;
}
});
return rootView;
}
private void webViewGoBack(){
mWebView.goBack();
}
}
你可以用我的解決方案:https://stackoverflow.com/a/45430033/3999826 –