2016-12-09 96 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(); 
} 

但是,你可能應該之前做出這一決定「首選項」片段將啓動,以便在創建「首選項」片段時不會啓動另一個片段。這只是一個良好實踐的建議。

讓我知道如果你在此之後仍然卡住。樂於幫助!