0

The code I used below works well, but when the screen orientation gets changed, isback becomes false again and turns into obsolete as well.

What I've tried so far:

boolean isback =false;

fragmentShowButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        isback = true;
        fragmentsShow();
    }
});

@Override
public void onBackPressed() {     
    if(isback == true) {
         super.onBackPressed();
    } else {
        // Do nothing
    }
}

And I don't want to use isVisible methods of Fragments, because I have to check so many Fragments in one activity and I can't tag all of them.

sourav.bh
  • 467
  • 1
  • 7
  • 20
mouse1
  • 43
  • 7
  • When the screen orientation changes, the activity restarts. Try using [Share Preferences](https://developer.android.com/guide/topics/data/data-storage#pref) if you want to store the some important data, even after activity closes. Read about the Activity Lifecycle for more understanding. – arc Mar 30 '19 at 17:03
  • Thank you I solved the problem with the Share Preferences – mouse1 Mar 30 '19 at 17:14
  • The data stored in Shared preferences will be not deleted even after your app is closed. Use it wisely. – arc Mar 30 '19 at 17:15
  • Aww It has another problem I have to set isBack to false in every fragments(more than 30) which create MainActivity(Originally, it was ResultActivity). The problem was solved anyway. Thank you – mouse1 Mar 30 '19 at 18:03
  • @mouse1 You could extend all your fragments from a base class, and set the flag there. – nasch Mar 31 '19 at 13:50

1 Answers1

1

Your activity restarts when screen orientation changes, causing isBack value to be false.

Simply add android:configChanges="orientation" to your activity details in the manifest. This will tell your activity not to recreate itself when rotating.

More reference

ronginat
  • 1,910
  • 1
  • 12
  • 23