2015-06-06 59 views
2

我有一個活動MainActivity,它在七個片段之間交換。該片段有沒有特定的順序,因此當應用程序被啓動,該活動是第一次創建,我設置一個作爲默認/啓動屏幕:在活動和更新視圖之間導航

FragmentManager fm = getSupportFragmentManager(); 
Fragment fragment = fm.findFragmentById(R.id.fragmentDrawerContainer); 

if (fragment == null) 
{ 
    fm.beginTransaction() 
      .add(R.id.fragmentDrawerContainer, new DefaultFragment()) 
      .commit(); 

    // An int I use to track which Fragment is currently being viewed, 
    // for navigation drawer purposes 
    mCurrentPosition = DEFAULT_FRAGMENT_POSITION; 
} 

從抽屜式導航,用戶還可以去新活動SettingsActivity,其中託管PreferenceFragment以更改某些設置,如度量單位(公制與英制)和顏色主題。

// Standard navigation from one activity to another from inside selectItem() method of nav drawer 
Intent intent = new Intent(this, SettingsActivity.class); 
startActivity(intent); 

一旦用戶從SettingsActivity導航回MainActivity,無論是背部或向上按鈕,我需要兩件事情:

1)用戶在看最後的片段仍必須那裏。目前,活動重新加載DefaultFragment(因爲活動正在重新創建,我認爲)。

2)每個片段包含自定義視圖我已經寫了,並在視圖必須從SettingsActivity用戶返回後利用SharedPreferences值自動更新。

爲了解決#1,我嘗試過使用android:launchMode="singleTop",它可以工作,但是我無法獲取視圖刷新,除非我切換到另一個片段然後再回來。

我已經試過在onResume()這個片段的方法中調用myView.invalidate(),但它似乎不起作用。

任何想法?如果我不清楚,請告訴我。先謝謝你!

+0

使用backstack來查看當前正在顯示的人是誰[0](http://stackoverflow.com/questions/30416815/can-i-put-a-fragment-on-backstack-which-hasnt-been-initialized -yet/30417083#30417083),[1](http://stackoverflow.com/questions/30686186/android-show-back-button-depending-on-backstack-count/30686674#30686674),[2](http ://stackoverflow.com/questions/30493716/is-there-a-way-to-listen-to-fragmenttransactions-of-a-fragmentmanager/30493931#30493931)..有些是間接的。即時通訊猜你是在錯誤的片段上調用它 – Elltz

回答

0

1)使用MainActivity中的onSaveInstanceState方法保存當前片段。 在onCreate方法中恢復它。

public void onCreate(Bundle savedInstanceState) { 
    ... 
    if (savedInstanceState != null) { 
     //Restore the fragment's instance 
     mContent = getSupportFragmentManager().getFragment(
        savedInstanceState, "mContent"); 
     ... 
    } 
    ... 
} 

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 

//Save the fragment's instance 
getSupportFragmentManager().putFragment(outState, "mContent", mContent); 


} 

在片段,通過覆蓋的onSaveInstanceState保存實例狀態和onActivityCreated恢復:

public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    ... 
    if (savedInstanceState != null) { 
     //Restore the fragment's state here 
    } 
} 
... 
@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 

//Save the fragment's state here 


} 

檢查this

2)在您的片段的的onResume方法get您共享偏好和設置它來查看:

SharedPreferences preferences =  this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE); 
String value = preferences .getString("key", "default_value");