片段中未调用 onSaveInstanceState

Posted

技术标签:

【中文标题】片段中未调用 onSaveInstanceState【英文标题】:onSaveInstanceState is not being called in Fragment 【发布时间】:2014-01-20 10:36:50 【问题描述】:

我知道有人问过这个问题,但我遵循了所有答案,但我仍然遇到同样的问题。我有两个脚本一个是片段管理器(IngredientsActivity),另一个是片段(OtherList)。代码如下

IngredientsActivity

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;



public class IngredientsActivity extends FragmentActivity implements ActionBar.TabListener 

    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    @Override
    public void onCreate(Bundle savedInstanceState) 

        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_list);

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // For each of the sections in the app, add a tab to the action bar.
        actionBar.addTab(actionBar.newTab().setText("Alcahol").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Juice").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Other").setTabListener(this));
    

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) 

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) 
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        
    

    @Override
    public void onSaveInstanceState(Bundle outState) 
        super.onSaveInstanceState(outState);          //OVERRIDE SAVE ON MAINCLASS

        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 

        return true;
    



    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 


        if (tab.getPosition() == 0) 
            AlcoholList simpleListFragment = new AlcoholList();
            getSupportFragmentManager().beginTransaction().replace(R.id.containert, simpleListFragment).commit();
         
        else if (tab.getPosition() == 1) 
            JuiceList androidlidt = new JuiceList();
            getSupportFragmentManager().beginTransaction().replace(R.id.containert, androidlidt).commit();
        



        else 

            OtherList androidversionlist = new OtherList();
            getSupportFragmentManager().beginTransaction().replace(R.id.containert, androidversionlist).commit();

        
    

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    

       public static class DummySectionFragment extends Fragment 
        public DummySectionFragment() 
        

        public static final String ARG_SECTION_NUMBER = "section_number";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) 
            TextView textView = new TextView(getActivity());
            textView.setGravity(Gravity.CENTER);
            Bundle args = getArguments();
            textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
            return textView;
        
    




其他列表

import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;


public class OtherList  extends ListFragment
    MyCustomAdapter dataAdapter = null;
    private  ArrayList<String> recipesList;
private ArrayList<Items> stateList ;

public OtherList() 

    setRetainInstance(true);
     stateList = new ArrayList<Items>();

          Items _states1 = new Items ("Gin",false);
          stateList.add(_states1);
Items _states2 = new Items ("Ginger Liqueur",false);
          stateList.add(_states2);
Items _states3 = new Items ("Citrus Vodka",false);
          stateList.add(_states3);
Items _states4 = new Items ("Champagne",false);
          stateList.add(_states4);
Items _states5 = new Items ("Coconut Rum",false);
          stateList.add(_states5);
Items _states6 = new Items ("Pear Vodka",false);
          stateList.add(_states6);
Items _states7 = new Items ("Rum",false);
          stateList.add(_states7);
Items _states8 = new Items ("Tequila",false);
          stateList.add(_states8);
Items _states9 = new Items ("Triple Sec",false);
          stateList.add(_states9);
Items _states10 = new Items ("Kahlua",false);
          stateList.add(_states10);

        


    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);


          dataAdapter = new MyCustomAdapter(this.getActivity(),R.layout.da_item, stateList);
          setListAdapter(dataAdapter);    

    


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 

        return inflater.inflate(R.layout.list_fragment, container, false);
    

    @Override
    public void onListItemClick(ListView list, View v, int position, long id) 


    

    private class MyCustomAdapter extends ArrayAdapter<Items>


 private ArrayList<Items> stateList;

public MyCustomAdapter(Context context, int textViewResourceId, 

ArrayList<Items> stateList) 

      super(context, textViewResourceId, stateList);
      this.stateList = new ArrayList<Items>();
      this.stateList.addAll(stateList);


  private class ViewHolder
  

    CheckBox name;
  

  @Override
 public View getView(int position, View convertView, ViewGroup parent) 
  

          ViewHolder holder = null;

          Log.v("ConvertView", String.valueOf(position));

          if (convertView == null)
          

             LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

             convertView = vi.inflate(R.layout.da_item, null);

            holder = new ViewHolder();

            holder.name = (CheckBox) convertView.findViewById(R.id.ingredientbox);

            convertView.setTag(holder);

                      holder.name.setOnClickListener( new View.OnClickListener() 
                      
                                 public void onClick(View v)  
                                 
                                   CheckBox cb = (CheckBox) v;
                                   Items _state = (Items) cb.getTag();
                                   _state.setSelected(cb.isChecked());
                                
                      );

          
          else
          
              holder = (ViewHolder) convertView.getTag();
          

          Items state = stateList.get(position);


          holder.name.setText(state.getName());
          holder.name.setChecked(state.isSelected());

          holder.name.setTag(state);

          return convertView;
  



@Override
public void onActivityCreated(Bundle savedInstanceState)
    super.onActivityCreated(savedInstanceState);





     @Override 
     public void onSaveInstanceState(Bundle outState) 
          Log.d("hey","SAVING");                              //NOT SAVING
         super.onSaveInstanceState(outState);
         save();

         outState.putStringArrayList("index", recipesList); 

         

                
            


    

    

我发现了多个建议覆盖 onSaveInstanceState ,我这样做了,我发现更多的建议告诉我使用 setRetainInstance。如果我想保存列表的值,我不知道为什么 setRetainInstance 状态会有所帮助。 我的问题-为什么不调用 OtherList 类中的保存,或者如果我想将值保存在列表视图中,有什么更好的方法来实现(在这种情况下,我使用的是复选框) p>

【问题讨论】:

你的问题到底是什么? 您希望 onSaveInstanceState() 何时被调用? 我的问题-为什么在OtherList类中没有调用save @svenoaks 在我更改选项卡或更改活动时在 OtherList 类中 【参考方案1】:

我遇到了类似的问题,我试图让 Fragment 保存其状态,但在 FragmentTransaction.replace() 上没有调用 onSaveInstanceState()。我试图为此找到解决方案并想,如果 Fragment 本身无法保存自己的状态,那么无论做什么替换都无法保存它。所以我做了这样的事情:

在 Fragment 中有一个名为 getState() 的方法或任何你想要的方法:

public Bundle getState()

    // save whatever you would have in onSaveInstanceState() and return a bundle with the saved data

然后在宿主对象中,在替换 Fragment 之前将该包保存到其实例变量中,并在切换回来时将参数设置为该保存的包。

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// assume Fragment a exists and you're trying to save the state and "state" is an instance variable
state = a.getState();
ft.replace(android.R.id.content, b);

然后在换回 Fragment a 时,您会将捆绑包作为参数传递。

a.setArguments(state);
ft.replace(android.R.id.content, a);

我没有深入研究您的代码,但听起来与您描述的问题相似。

【讨论】:

是否可以在 "replace" 之后立即调用 "setArguments" ?还是不久之后? 你可以反转状态的人口。片段可以在准备好时获取它,而不是设置它的活动。【参考方案2】:

onSaveInstanceState() 仅在 Android 系统可能需要重新创建 Fragment 的特定实例时调用。有很多实例会从 Fragment 中导航出来,甚至在不调用它的地方销毁 Fragment。请查阅文档以获取更多信息,也请阅读Activity.onSaveInstanceState() 文档,因为这也适用于此处:http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle) http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

编辑:在您的情况下,每次用户导航回片段时,您都不能重新创建片段。我建议考虑 ViewPager 和 FragmentPagerAdapter 来自动管理片段。也可以看看这个帖子:ViewPager and fragments — what's the right way to store fragment's state?

【讨论】:

那我应该如何在片段中保存一些东西? 你想做什么?无论如何,您似乎每次都在重新创建它。如果您确实需要保存某些内容,则始终调用 onPause()。 OtherList 是列表视图中的一堆复选框,当用户离开列表视图时,我想保留哪些复选框被选中。 好的,即使用户完全离开应用程序,您是否希望它们保持检查状态? 可能最好的方法是在 SharedPreferences 中保存状态或在 onPause() 中将 List 保存到文件中

以上是关于片段中未调用 onSaveInstanceState的主要内容,如果未能解决你的问题,请参考以下文章

片段中未调用 onAttach()

片段android中未调用onActivityResult [重复]

Android:片段在活动结果合同中未收到 RESULT_OK

FragmentContainerView 中未调用/显示 OnMapReady

AppSync 示例应用程序中未生成片段

getSupportFragmentManager() 在活动扩展片段中未定义