比方說你有3個碎片A,B和C
我給指數的每個片段這樣說0- > A,1-> B,2-> C。所以,當我這樣做,我也拯救像下面的代碼索引:
Fragment newFragment = new A();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out);
transaction.replace(R.id.frame_layout, newFragment);
transaction.commit();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("last_fragment", 0);//For fragment A saving index 0
editor.commit();
然後在的onCreate就可以,如果使用的情況下是這樣的:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
//0 here is the default value
int lastFragment = sharedPref.getInt("last_fragment", 0);
然後你就可以做到這一點
switch(lastFragment){
case 0:
//Load your fragment Here according to the index.
break;
case 1:
//Load your fragment Here according to the index.
break;
case 2:
//Load your fragment Here according to the index.
break;
}
希望這會有所幫助。
將此置於創建活動。所以無論何時創建活動,都會將該片段添加到該片段中。 –
實際上我想在點擊按鈕時應用這個片段 –
使用共享的首選項,那麼你可以通過索引所有片段來保存索引。然後在onCreate中檢查最後一個片段是什麼並加載它。 –