how to access the webview inside the onBackPressed method on android

Asked

Viewed 68 times

1

Hello, I’m trying to implement the back to the home of my applicator, my app is all built inside the webview, I need to call the javascript Function to return home, because when I click on the back arrow of android it was simply closing my app, so I did:

@Override
public void onBackPressed() {

}

With that he just doesn’t do anything when pressing there, only that I wanted to go to home of my app... But this method does not have access to the webview variable, someone knows how to access the webview within this method?

  • Hello @Ecchinya, Welcome to Sopt, with the code you added gets a little tricky to help, you would need to add for example information from where you are creating the webview, if this variable is property of the class, etc... [mcve] - it is worth taking a look at our [Tour]

  • Without this information you can’t help much. I would make the webview run a javascript to let you know that the back button has been clicked. Something like mWebView.evaluateJavascript("onBackPressed()"); within that event there

  • So, Icaro Martins, I create it so setContentView(R.layout.activity_main); Webview Webview = (Webview) this.findViewById(R.id.web); it is created within the onCreate method

  • I need to access this Webview variable within the onBackPressed method

1 answer

0


So its class was commented this +/- so

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // ...
         setContentView(R.layout.activity_main); 
         WebView WebView = (WebView) this.findViewById(R.id.web);
         /// ^ esta definida localmente
    // ...
    }

    @Override
    public void onBackPressed() {

    }

}

You can do something as shown below, basically instead of defining the variable within the method onCreate you set it at the root of the class, so it will be visible to other methods/functions:

public class MainActivity extends Activity {

    public WebView mWebView=null; /// <- definir como propriedade da classe
                                  ///    assim ela vai ficar acessível em outros métodos

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // ...
         setContentView(R.layout.activity_main); 
         mWebView = (WebView) this.findViewById(R.id.web);
    //     ^ associar a webview do layout
    // ...
    }

    @Override
    public void onBackPressed() {

        if( mWebView != null )
        {
             mWebView.evaluateJavascript("onBackPressed()");
        }    

    }

}
  • 1

    Thanks, it worked :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.