简体   繁体   中英

WebView is closing when I press the button back android keyboard

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}

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();
    }
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM