2016-12-09 10 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

"以前に開かれた"ということを明確にすることはできますか?あなたは、アプリケーションを使用している間、ユーザーが少なくとも1回フラグメント/スクリーンを開いたことを意味しますか?または、アプリケーションが終了してユーザーが後で元の状態に戻った場合、「前に開かれました」ブール値をリセットする必要がありますか? また、あなたの '(私はここに何を置くの?)'では、コンテナビューのID(通常はアクティビティのレイアウトのFrameLayoutビュー)で置き換えることができます。ここでの回答を参照してください:http://stackoverflow.com/questions/11620855/replacing-fragments-isnt-working-am-i-executing-this-the-properway – w3bshark

+0

最初の "あなたはユーザーが開いたことを意味しますか?アプリを使用している間、少なくとも1回はフラグメント/画面? – Coder

答えて

0

ユーザーがonCreateで、このPreferencesView断片を見た後は、ユーザーのためのブール持続:

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

をしかし、あなたはおそらく前に、この決意をするべきですプリファレンスフラグメントは、プリファレンスフラグメントの作成中に別のフラグメントを開始しないように開始されます。これは良い練習のための示唆にすぎません。

あなたがこの後にまだ立ち往生している場合は教えてください。お力になれて、嬉しいです!

関連する問題