我想为我的webview片段实现后退按钮,在stackoverflow上尝试不同的答案,无法使用我的代码。
以下是我的代码。
public class LoginFragment extends Fragment {
public LoginFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://example.com/");
return rootView;
}
}
我甚至试过这个,在developer.android.com上找到它
public boolean WebViewGoBack() {
if(webView.canGoBack()){
webView.goBack();
return true;
}
return false;
}
感谢您的帮助。
答案 0 :(得分:0)
试试这个:
@Override
public void onBackPressed() {
if (webView.canGoBack()) { //Gets whether this WebView has a back history item.
webView.goBack(); //this takes to the previous page
} else {
super.onBackPressed();// it finishes the current activity
}
}
答案 1 :(得分:0)
public class LoginFragment extends Fragment {
public LoginFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://example.com/");
webView.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
handler.sendEmptyMessage(1);
return true;
}
return false;
}
});
return rootView;
}
}
}