0

I'm trying to make a fragment so that if it has been opened before stay on the same page or if not go to a different fragment. It seems that anything I've tried doesn't work. Please Help.

My Code:

public class PreferencesView extends Fragment {

    public static boolean Preferences_Opened = false;


    public void changePreferences() {
        if (!Preferences_Opened) {
            PreferencesChange newFragment = new PreferencesChange();

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            transaction.replace((What am I supposed to put here?), newFragment);
            transaction.addToBackStack(null);

            transaction.commit();
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        View rootView = inflater.inflate(R.layout.activity_preferences_view, container, false);

        changePreferences();

        //Other non-important stuff here



        return rootView;
    }

}
Coder
  • 67
  • 1
  • 9
  • Can you clarify what you mean by "has been opened before"? Do you mean that the user has opened the fragment/screen at least once throughout using the app? Or does the "has been opened before" boolean need to be reset if the app closes and the user comes back at a later point in time? Also, for your `(What am I supposed to put here?)`, you can replace that with the id of your container view (usually a FrameLayout view in your activity's layout). See answers here: http://stackoverflow.com/questions/11620855/replacing-fragments-isnt-working-am-i-executing-this-the-proper-way – w3bshark Dec 10 '16 at 00:41
  • The first, "Do you mean that the user has opened the fragment/screen at least once throughout using the app?" – Coder Dec 10 '16 at 01:18

1 Answers1

0

Once the user has viewed this PreferencesView Fragment, in onCreate, persist a boolean for the user:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
boolean preferencesHasBeenOpened = prefs.getBoolean("preferencesHasBeenOpened", false);
if (!preferencesHasBeenOpened) {
    prefs.edit().putBoolean("preferencesHasBeenOpened", true).apply();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.activity_fragment_container, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

But, you should probably be making this determination before the Preferences fragment is initiated so that you're not starting another fragment during the creation of your Preferences fragment. This is just a suggestion for good practice.

Let me know if you're still stuck after this. Happy to help!

w3bshark
  • 2,700
  • 1
  • 30
  • 40