标签主机片段保存实例

时间:2014-09-06 06:35:57

标签: android android-fragments android-tabhost savestate fragment-tab-host

我有一个带有5个标签的Tabhost:tab1,tab2,tab3,tab4,tab5
并且它们都具有相同的片段,内容不同 我的片段onCreateView方法有以下代码:

switch(tabtag){
   case 1:
       loaddata1();
       break;
   case 2:
       loaddata2();
       break;
   case 3:
       loaddata3();
       break;
   case 4:
       loaddata4();
       break;
   case 5:
       loaddata5();
       break;
}

我正确加载了相关数据,但我希望每次只为每个标签加载一次数据 我使用onSaveInstanceStateonActivityCreated方法:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean("1", isFirsttime1);
    outState.putBoolean("2", isFirsttime2);
    outState.putBoolean("3", isFirsttime3);
    outState.putBoolean("4", isFirsttime4);
    outState.putBoolean("5", isFirsttime5);
    outState.putBoolean("6", isFirsttime6);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state for checked position.
        isFirsttime1 = savedInstanceState.getBoolean("1");
        isFirsttime2 = savedInstanceState.getBoolean("2");
        isFirsttime3 = savedInstanceState.getBoolean("3");
        isFirsttime4 = savedInstanceState.getBoolean("4");
        isFirsttime5 = savedInstanceState.getBoolean("5");
        isFirsttime6 = savedInstanceState.getBoolean("6");

    }
}

所以在onCreateView我在每个开关案例中添加了这段代码:

if (isFirsttime){
   loaddata();
}
else{
   //use from my view state
}

但它不能像那样工作,我认为因为我再次使用相同的片段,onSaveInstanceState方法没有被调用。

我该怎么解决呢? 提前谢谢。

0 个答案:

没有答案