2016-12-09 85 views
0

我试图做一个片段,以便如果它已经打开之前留在同一页面上,或者如果不去到不同的片段。看来,我尝试过的任何东西都不起作用。请帮忙。从片段切换到另一个片段如果片段尚未打开

我的代码:

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; 
    } 

} 
+0

你能说清楚你以前打开过什么吗?你的意思是用户在使用该应用程序的过程中至少打开过一次片段/屏幕?或者如果应用程序关闭并且用户在以后的时间点回来,“之前已打开”布尔值需要重置?另外,对于你的'(我应该放在这里吗?)',你可以用你的容器视图的id(通常是你的活动的布局中的FrameLayout视图)替换它。在这里看到答案:http://stackoverflow.com/questions/11620855/replacing-fragments-isnt-working-am-i-executing-this-the-proper-way – w3bshark

+0

第一,“你的意思是用户已打开片段/屏幕至少在整个使用应用程序一次?“ – Coder

回答

0

一旦用户认为这一PreferencesView片段,在onCreate,坚持为用户的布尔:

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(); 
} 

但是,你可能应该之前做出这一决定“首选项”片段将启动,以便在创建“首选项”片段时不会启动另一个片段。这只是一个良好实践的建议。

让我知道如果你在此之后仍然卡住。乐于帮助!