I have an app in which I have a WebView
where I display some websites. It works, clicking a link in the webpage goes to the next page in the website inside my a
Official Kotlin Way:
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// Check if the key event was the Back button and if there's history
if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
myWebView.goBack()
return true
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event)
}
https://developer.android.com/guide/webapps/webview.html#NavigatingHistory
use this code to go back on page and when last page came then go out of activity
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(LiveImage.this,DashBoard.class);
startActivity(intent);
}
Here is the Kotlin solution:
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
if (event?.action != ACTION_UP || event.keyCode != KEYCODE_BACK) {
return super.onKeyUp(keyCode, event)
}
if (mWebView.canGoBack()) {
mWebView.goBack()
} else {
finish()
}
return true
}
Full reference for next button and progress bar : put back and next button in webview
If you want to go to back page when click on phone's back button, use this:
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
You can also create custom back button like this:
btnback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (wv.canGoBack()) {
wv.goBack();
}
}
});
If someone wants to handle backPressed for a webView inside a fragment, then he can use below code.
Copy below code into your Activity
class (that contains a fragment YourFragmmentName
)
@Override
public void onBackPressed() {
List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
boolean handled = false;
for(Object f: fragmentList) {
if(f instanceof YourFragmentName) {
handled = ((YourFragmentName)f).onBackPressed();
if(handled) {
break;
}
}
}
if(!handled) {
super.onBackPressed();
}
}
Copy this code in the fragment YourFragmentName
public boolean onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
return true;
} else {
return false;
}
}
Notes
Activity
should be replaced with the actual Acitivity class you are using.YourFragmentName
should be replaced with the name of your Fragment.webView
in YourFragmentName
so that it can be accessed from within the function.In kotlin:
override fun onBackPressed() {
when {
webView.canGoBack() -> webView.goBack()
else -> super.onBackPressed()
}
}
webView - id of the webview component in xml, if using synthetic reference.