当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Switching from fragment to another fragment if fragment has not been opened before

问题描述:

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;

}

}

网友答案:

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!

分享给朋友:
您可能感兴趣的文章:
随机阅读: