Reputation: 55
I'm trying to program for android and I'm having a little problem. I made an app, but I can not make the back of the phone button, return to the previous page without completely closing the app. I'm working with WebView.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
// CODIGO DO WEB VIEW
final WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl("http://www.idestudos.com.br");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
myWebView.setWebViewClient(new MyBrowser());
myWebView.setWebViewClient(new WebViewClient() { //CODE WEBVIEW}
Upvotes: 1
Views: 2075
Reputation: 1251
Easy implemented by calling canGoBack.
if(webView.canGoBack()) {
webView.goBack();
}
And calling it from inside onBackPressed method in activity like this:
@Override public void onBackPressed() {
if(webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
Upvotes: 2
Reputation: 1466
Here's a solution:
When your WebView overrides URL loading, it automatically accumulates a history of visited web pages. You can navigate backward and forward through the history with goBack() and goForward().
For example, here's how your Activity can use the device Back button to navigate backward:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
Check out the Building Web Apps in WebView Android Developers Guide for more info
Hope it helps you!
Upvotes: 1