-1

I have 2 activities and 4 fragments. I just want the code to close only when the user is on the MainActivity or welcome_fragment (I have named it that way)

I wrote some pseudocode below to help you understand my question:

Note: This code should be written under onBackPressed method in MainActivity

if(currentactivity/currentfragment)==MainActivity/welcome_fragment)
{
    super.onBackPressed();
}

How do I get the current fragment or activity's id to compare it with "R.id.welcome_fragment" (or something else) and then and only then close the app onbackpressed?

David Medenjak
  • 33,993
  • 14
  • 106
  • 134

2 Answers2

0

Not sure I understand the "on the MainActivity" requirement as overriding onBackPressed in the MainActivity ensures that it only runs there. As far as the welcome_fragment is concerned you can do this:

public class MainActivity extends ... {

    @Override
    public void onBackPressed(){
        final Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.primary_content);
        if (WelcomeFragment.class.isInstance(currentFragment)) {
            // The current fragment is a WelcomeFragment. Do something here...
            super.onBackPressed();
        }
    }
}

Replacing R.id.primary_content with the id of your fragment container and WelcomeFragment with the actual class that is your welcome_fragment.

Cory Charlton
  • 8,868
  • 4
  • 48
  • 68
0

The only place you should call super.onBackPressed() is in an override of onBackPressed(). If that override is in MainActivity, and you haven't extended MainActivity, there's no need to test what activity is running.

It sounds like what you really want to do is override onBackPressed() in the other activity and have it not call super. Be warned that changing the behavior of the navigation bar buttons is generally bad UX and may lead to uninstalls.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82