Reputation: 29867
When using the normal mobile browser, when you press the Back button, it takes you to the previous page. When a WebView is used in my app to display a web page and the user wants to return to the previous page, how is typically done? Does pressing the Back button automatically take the user back to the previous page or does it take them back to the previous Activity? I would assume that since the Back button is normally meant to take the user to the previous activity, it shouldn't be used to return to a previous web page. If this is the case, should my mobile web page include its own Back link that a user clicks on?
I guess what I am trying to do is to understand the correct behavior I should be employing.
Upvotes: 2
Views: 8838
Reputation: 54672
Let's look at some popular browser. currently, in my device, there are two browsers
In both browsers, it goes to the previous page. So it is a common behavior. to do so
you can overwrite the onBackPressed
to go to your previous page.
@Override
public void onBackPressed(){
if(mWebView.canGoBack() == true){
mWebView.goBack();
}
else{
finish();
}
}
Upvotes: 6
Reputation: 33996
Please keep in mind that back buttons is coming with majority of the android devices. So you do not need a back button in your activity to go back to previous activity.
And about the webview if you want navigation in the webview to travel all the previous pages then you can put a back button and implement the navigation of the webview using the method webview.goBack()
.
In short, If you want your user to navigate to previous page then you should give functionality of the webview to go back to previous page and from the first page user click on back button again finish the activity.
Upvotes: 2
Reputation: 14128
Something like this in activity with WebView:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(yourWebView.canGoBack() == true){
yourWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
or override onBackPressed method:
@Override
public void onBackPressed() {
if(yourWebView.canGoBack() == true){
yourWebView.goBack();
} else {
finish();
}
}
Upvotes: 0
Reputation: 216
When you are clicking back button, you are clicking it for activity that is opening the webview better thing would be to give a back button in you layout..and hence saving the last url opened by user
Upvotes: 0
Reputation: 11112
You can use this override the onkeydown event and check the key pressed (in this case is back key) and check if is there any previous page
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(yourWebView.canGoBack() == true){
yourWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 1