How to Add "Go Back" Function in Webview Inside Fragment

Back button in android webview within a fragment

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());

How to make WebView inside fragment to go back to previous tab?

You can implement setOnKeyListener on webview to handle back button.

mWebview.setOnKeyListener(new View.OnKeyListener(){

public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& mWebview.canGoBack())
{
mWebview.goBack();
return true;
}
return false;
}

});

If there is no previous page in your webview then it will trigger usual onBackPressed.

Hope it helps you.

Fragment with Webview utilize harware back button to go to previous webpage

Try overriding onBackPressed() in your Activity and make it poke the WebView.

BTW - you could post the piece of Activity containing the onKeyDown method as well.

EDIT: Instead of making your methods static and accessing them the way you do now (BlogFragment.canGoBack()), first instantiate the fragment:

BlogFragment blogFragment = new BlogFragment();
blogFragment.canGoBack();

and then just remove the static from your methods. :)

OPs implementation (with thanks to Klotor)
At the head of MainActivity implement:

BlogFragment blogFragment = new BlogFragment();

Then implement:

public void onBackPressed() {

blogFragment.canGoBack();
if(blogFragment.canGoBack()){
blogFragment.goBack();
}else{
super.onBackPressed();
}

}

The fragment is instantiated outside of the onBackPressed in order to prevent crashing when using a method to navigate between fragments.
In this case you need to instantiate a newinstance of the fragment, rather than a whole new fragment.



Related Topics



Leave a reply



Submit