Back Button In Android Webview Within A Fragment
Solution 1:
You can override the Activity's onBackPressed() method and check if there is any previous fragment in the backstack to pop back by calling getFragmentManager().popBackStackImmediate() or getSupportFragmentManager().popBackStackImmediate() like the code below:
@Override
public void onBackPressed() {
if (!getFragmentManager().popBackStackImmediate()) {
super.onBackPressed();
}
}
Don't forget to call .addToBackStack(null) before you call commit() to add the fragmenttransaction to the backstack.
And if you want to press back button to go back to previous webpage user has navigated in the WebView before go back to previous fragment, you can do this:
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else if (!getFragmentManager().popBackStackImmediate()) {
super.onBackPressed();
}
}
And remember to set your webView to load any webpage in the WebView by calling webView.setWebViewClient(new WebViewClient());
Solution 2:
If you use the Web fragment and other fragments in your activity, this code works:
In your Activity:
@OverridepublicvoidonBackPressed() {
DrawerLayoutdrawer= (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
// Webview backif (getSupportFragmentManager().findFragmentById(R.id.fragment_content) instanceof YourWebFragment){
finalYourWebFragmentwebFragment= (YourWebFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_content);
if (webFragment != null){
if (webFragment.onBackPressed()){
return;
}
}
}
// Fragments backif (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
In your Web Fragment:
publicbooleanonBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
returntrue;
}
returnfalse;
}
Reference: https://stackoverflow.com/a/19268540/1329094 and https://stackoverflow.com/a/10631591/1329094
Solution 3:
In Kotlin you can achieve this by adding setOnKeyListener to your WebView. This listener responds to clicks on the device's hardware buttons.
overridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val myWebView: WebView = view.findViewById(R.id.your_webView)
myWebView.webViewClient = WebViewClient()
myWebView.loadUrl("https://www.google.com/")
myWebView.setOnKeyListener { v, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
myWebView.goBack() // Navigate back to previous web page if there is one
nested_scroll.scrollTo(0, 0) // Scroll webview back to top of previous page
}
true
}
}
Post a Comment for "Back Button In Android Webview Within A Fragment"