Dev Sharma
Dev Sharma

Reputation: 674

How to go to previous page in Webview present in a Fragment?

I have an actvity called SearchActivity. It has a searchbar and 4 tabs with Webviews. When I enter text and click on search, all the tabs are loading respective urls that I'm passing to them. But when I click on back button I want all the webviews to go back to the previous page, instead the activity closes. I've tried the below code, but it doesn't work. This the code of SearchActivity

public boolean onKeyDown(int keyCode, KeyEvent event) {

    int count = getFragmentManager().getBackStackEntryCount();

    if (count != 0 && (keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
        webView.goBack();
        getFragmentManager().popBackStack();
        //additional code
    } else {
        super.onBackPressed();
    }
    return super.onKeyDown(keyCode, event);
}

Upvotes: 1

Views: 149

Answers (2)

touhid udoy
touhid udoy

Reputation: 4442

1.Add an interface on SearchActivity and implement that interface on MyFragment to communicate between SearchActivity and MyFragment.

2.Override onBackPressed() method of SearchActivity to add custom functions when the back button is pressed and check if fragment's WebView can go back via goBack listener. If can go back, then do so. If can not, call super.onBackPressed().

SearchActivity.java

public class SearchActivity extends AppCompatActivity{

public interface goBack{
    boolean canGoBack();
}

@Override
public void onBackPressed() {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
   //fragment_container is a layout where fragment is populated

    if (fragment instanceof goBack && fragment.canGoBack()) {
        return;
    }
    super.onBackPressed();

}
}

MyFragment.java

public class MyFragment extends Fragment implements SearchActivity.goBack{
@Override
public boolean canGoBack() {
    if (webView.canGoBack()) {

        webView.goBack();
        return true;
    }
    return false;
}

Upvotes: 2

Nikos Hidalgo
Nikos Hidalgo

Reputation: 3756

I would use an interface:

Public Interface InterfaceBackPressed {
    onInterfaceBackPressed();
}

Then in your Activity:

public class SearchActivity extends Activity {
...
    @Override public void onBackPressed() {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
       if (!(fragment instanceof InterfaceBackPressed) || !((InterfaceBackPressed) fragment).onBackPressed()) {
          super.onInterfaceBackPressed();
       }
    } 
}

and have every fragment implement your interface:

public class MyFragment extends Fragment implements IOnBackPressed{
   @Override
   public void onInterfaceBackPressed() {
       if (webView.canGoBack()) {

            webView.goBack(); 
        } else {
        super.onInterfaceBackPressed();
        }
    }
}

Upvotes: 1

Related Questions