I am working on a webview android app. I am unable fix a 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.
We can use webview method to navigate forward and backward. method boolean
canGoForward()
for Gets whether this WebView has a forward history item.canGoBack()
for Gets whether this WebView has a back history item.goBack()
Goes back in the history of this WebView andgoForward()
Goes forward in the history of this WebView. this is my implementation :Add this in your
Activity
code (not inonCreate()
or nested anywhere else)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
returntrue
or you won't load any links.In your code you have kept the following block in onCreate() method.
Instead keep the same code in onBackPressed() like this
also refer to Getting Started: WebView-based Applications for Web Developers in Android