2

I recently started to program with Android studio, I came across a problem. I created a Webview application, and I would like to press the back button on the smartphone once you go back to the previously viewed page, while pressing it twice in a row will exit the application. For now I only managed to lock the back button. Do you have any advice? I am attaching the code written so far:

public class MainActivity extends AppCompatActivity {

@Override
public void onBackPressed() {

}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

WebView web=(WebView)findViewById(R.id.browser);
web.setWebViewClient(new WebViewClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("https://www.google.com");
Black
  • 18,150
  • 39
  • 158
  • 271
Simone.P
  • 21
  • 1

1 Answers1

1

You can manage onKeydown() method, It goes like this...

@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
    if (e.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (web.canGoBack())
                    web.goBack();
                else
                    finish();
                return true;
        }
    }
    return super.onKeyDown(keyCode, e);
}

By doing this you will be able to manage back press of website. Hope it help!

buzzingsilently
  • 1,546
  • 3
  • 12
  • 18