Shakti Patra
Shakti Patra

Reputation: 75

addToBackStack not working with onBackPressed method

I have created a tabbed activity inside a navigation drawer activity. I have linked the lists inside the navigation drawer with individual fragments. I also used the command ft.addToBackStack(null) before ft.commit(). It was perfectly fine and I was able to use it to close the fragments inside the navigation drawer. now I have created webviews inside the fragments of the tabbed activity (home page). I added the onBackPressed to go back inside the webview and now the addToBackStack method stopped working.

For the navigation drawer fragments,

private void dispaySelectedScreen(int id) {
    Fragment fragment = null;

    switch (id) {
        case R.id.fragment1:
            fragment = new Fragment1();
            break;
        case R.id.fragment2:
            fragment = new Fragment2();
            break;
        case R.id.fragment3:
            fragment = new Fragment3();
            break;
        case R.id.fragment4:
            fragment = new fragment4();
            break;
    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, fragment);
        ft.addToBackStack(null);
        ft.commit();
    }

onBackPressed Method

@Override
public void onBackPressed() {
    if (hWebView.canGoBack()) {
        hWebView.goBack();
    } else if (!getFragmentManager().popBackStackImmediate())

        if (sWebView.canGoBack()) {
            sWebView.goBack();
        } else if (!getFragmentManager().popBackStackImmediate())

            if (dWebView.canGoBack()) {
                dWebView.goBack();
            } else if (!getFragmentManager().popBackStackImmediate());



}

Please help me out!!!

Upvotes: 1

Views: 376

Answers (1)

rafsanahmad007
rafsanahmad007

Reputation: 23881

try this code: override onBackPressed() in your tabbed activity (home page).

@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    if (hWebView.canGoBack()) {
        hWebView.goBack();
    } else if (!getFragmentManager().popBackStackImmediate())
        if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack();
        } else {
            super.onBackPressed();
        }
}

Upvotes: 1

Related Questions