I am working on a WebView android app. I am unable to fix an issue in my app to back navigate. I am using this code and tried all modifications can be made to this.
public class DeviceActivity extends Activity {
private WebView web;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
web = (WebView) findViewById(R.id.webView);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
web.getSettings().setPluginsEnabled(false);
web.getSettings().setSupportMultipleWindows(false);
web.getSettings().setSupportZoom(false);
web.setVerticalScrollBarEnabled(false);
web.setHorizontalScrollBarEnabled(false);
// Our application's main page will be loaded
web.loadUrl("file:///android_asset/fbp/index.html");
web.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
public void onBackPressed() {
if (web.canGoBack()) {
web.goBack();
} else {
// My exit alert code goes here.
}
}
});
}
}
This doesn't navigate back but instead, it exits the app. Any help would be appreciated.
To get a callback when we press the back button, we need to wrap our view inside WillPopScope and create a method inside _WebViewWebPageState to check if webview can go back. If it can, then we perform the back operation. Otherwise, we'll show exit dialog.
Only when a callback is enabled (i.e., isEnabled() returns true ) will the dispatcher call the callback's handleOnBackPressed() to handle the Back button event. You can change the enabled state by calling setEnabled() . Callbacks are added via the addCallback methods.
Alternatives to WebView If you want to send users to a mobile site, build a progressive web app (PWA). If you want to display third-party web content, send an intent to installed web browsers. If you want to avoid leaving your app to open the browser, or if you want to customize the browser's UI, use Custom Tabs.
Add this in your Activity
code (not in onCreate()
or nested anywhere else)
@Override
public void onBackPressed() {
if (web.copyBackForwardList().getCurrentIndex() > 0) {
web.goBack();
}
else {
// Your exit alert code, or alternatively line below to finish
super.onBackPressed(); // finishes activity
}
}
This will navigate back through the WebView
history stack until it is empty and then perform the default action (in this case it finishes the activity).
You should probably also set your WebViewClient to have shouldOverrideUrlLoading
return true
or you won't load any links.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With