niyas  nazar
niyas nazar

Reputation: 42

Back Button pressed handler

I'm working on an app that need Navigation Drawer. This app has 1 MainActivity and about 10 fragments on it. When I click the Navigation Drawer icon in MainActivity it will show the 10 fragments so I can select each of them.

I choose fragment A, then B, then C...to F, for example. When I'm in fragment F and press the Back button, it will take me back to fragment E, then Back again it will take me to fragment D... What I need is when i press back button in fragment it need to go to the default home in navigationdrawer.

I've search on SO and found 1 similar question but no answer yet so I have to make another question

Upvotes: 1

Views: 665

Answers (7)

Jyubin Patel
Jyubin Patel

Reputation: 1373

Hi below is my solutions,

I am using below code to change the fragment:

fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();

if (fragmentA == null)
    fragmentA = new FragmentA();

fragmentTransaction.replace(R.id.container, fragmentA);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();

if you are using supportFragment then use getSupportFragmentManager() in place of getFragmentManager().

And When you perform backpress at that time Put below code into Your Activity which contains Fragment.

@Override
public void onBackPressed() {
    super.onBackPressed();
    getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

Hope this answer is helping you and solve your problem.

Upvotes: 3

Pratik j
Pratik j

Reputation: 11

Try the following code, it worked for me.

    rootView.setFocusableInTouchMode(true);
    rootView.requestFocus();
    rootView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {

                     final Intent startIntent = new Intent(context, MainActivity.class);
                     startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                     startActivity(startIntent);
                     getActivity().finish();

            }
            }
            return false;
        }
    });
    return rootView;

Upvotes: 1

Amardeep
Amardeep

Reputation: 1434

* The purpose of this method is set The current display ui
 *
 * @param id the ui that has to be displayed
 */
public void setDisplay(int id) {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    HideKeyboard.hideKeyboard(HomepageActivity.this);
    Intent intent;
    switch (id) {
        //Open up home fragment
        case AppConstants.DISPLAY_HOME:
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentHome)) {
                mFragment = new FragmentHome();
                replaceFragment(mFragment, AppConstants.HOME_FRAGMENT);
            }
            break;
        //opens up the setting section
        case AppConstants.DISPLAY_SETTING:
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentSetting)) {
                mFragment = new FragmentSetting();
                replaceFragment(mFragment, AppConstants.SETTING_FRAGMENT);
            }
            break;
        //display the logout dialog
        case AppConstants.DISPLAY_LOGOUT:
            DialogManager.getInstance().showLogOutLogOut(this);
            break;
        //display the notification section
        case AppConstants.DISPLAY_NOTIFICATION:
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentNotification)) {
                mFragment = new FragmentNotification();
                replaceFragment(mFragment, AppConstants.NOTIFICATION_FRAGMENT);
            }
            break;

        default:
            //Setup Home Fragment as default fragment
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentHome)) {
                mFragment = new FragmentHome();
                replaceFragment(mFragment, AppConstants.HOME_FRAGMENT);
            }
            break;
    }
}

/* * Insert the mFragment by replacing any existing mFragment * * @param fragment the fragment that has to be replaced * @param name the tag of the fragment */

public void replaceFragment(final Fragment fragment, final String name) {
          if(mFragmentManager.findFragmentById(R.id.fragment_container)instanceof FragmentHome) {
                mFragmentManager.beginTransaction()
                        .replace(R.id.fragment_container, fragment, name)
                        .addToBackStack(name)
                        .commit();
            } else {
                mFragmentManager.beginTransaction()
                        .replace(R.id.fragment_container, fragment).
                        commit();
            }
      }

/** * The purpose of this method is to remove the fragment from the stack */ public void removeFragmentFromStack() {

    if (mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentHome) {
        exitFromApp();
    } else {
        mFragmentManager.popBackStackImmediate();

    }
}

Upvotes: 1

valentino
valentino

Reputation: 216

I think you can try this. Add this in onBackPressed()

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
            getSupportFragmentManager().popBackStack();
        }
    } else {
        super.onBackPressed();

    }

Upvotes: 2

Azar Kazi
Azar Kazi

Reputation: 11

Try this In your manifest i think it will help you >

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Frame1"
            android:label="@string/frame_1"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.webservice.appname.MainActivity" />
        </activity>
        <activity
            android:name=".Frame2"
            android:label="@string/frame_2"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.webservice.appname.MainActivity" />
        </activity>
        <activity
            android:name=".Frame3"
            android:label="@string/frame_3"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.webservice.appname.MainActivity" />
        </activity>
        .
        .
        .
        .
        .
</application>

Upvotes: -1

SpiritCrusher
SpiritCrusher

Reputation: 21053

In this case do not add your Fragments to backStack. just replace each fragment if you do not want pop on onBackPressed().

getSupportFragmentManager().beginTransaction().replace(R.id.containerFrame, new AFragment()).commit();

Handle onBackPressed() :

@Override
public void onBackPressed() {
    Fragment frag = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
    if (frag instanceof HomeFragment) {
        // DO Onbackpress
        finish();
    } else {
        HomeFragment fragment = new HomeFragment()
        getSupportFragmentManager().beginTransaction().replace(R.id.containerFrame, fragment).commit();
    }
}

Upvotes: 1

Benjith Mathew
Benjith Mathew

Reputation: 1221

Did you tried

try {  
   activity.getSupportFragmentManager().popBackStackImmediate(n‌​ull,FragmentManager.POP_BACK_STACK_INCLUSIVE);
   } catch (IllegalStateException e)
  { 
     e.printStackTrace();
  }

Upvotes: 1

Related Questions