当前位置: 首页 > 面试题库 >

片段中未调用onSaveInstanceState

白昊乾
2023-03-14
问题内容

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

成分活动

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状态会有所帮助。
我的问题-为什么要在List View中保存值,为什么不调用OtherList类中的save或有什么更好的方法实现
(在这种情况下,我使用的是复选框)


问题答案:

onSaveInstanceState()仅在Android系统可能需要重新创建该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和fragments—存储fragment状态的正确方法是什么?



 类似资料:
  • 我有一个应用程序,得到了一个活动与2个碎片水平放置。 在我的活动中,我使用膨胀菜单,使用它我可以显示actionbar选项菜单。但是,当我试图从其中一个片段更新操作栏菜单项时,没有调用。因此,我无法更新操作栏选项菜单。

  • 我有一个片段,其中有recyclerview,并使用recyclerview适配器在这个recyclerview中设置数据。 现在,我在适配器的列表项中单击了一个按钮,我需要检查android中的READ\u EXTERNAL\u STORAGE权限,以查看android中的新权限模型。 我在这个适配器的片段中创建了一个新函数,用于检查是否授予了权限,如果尚未授予权限,则请求权限。 我已经通过了我

  • P.P.S@Philipp Jahoda,我实现了onCreateOptionsMenu(...)在片段的托管活动中。

  • 假设有两个Fragments,X和Y。我在X上添加Y片段。当Y完成它的工作,然后删除,X再次可见。 问题:当Y片段被删除并且X再次可见时,我必须执行一些任务,但不会调用,因为它取决于活动。那么我怎么知道片段是可见的呢?

  • 尝试在和中捕获它,如 并且我在中有。

  • 问题是,此AutoResolveHelper不是对片段调用onActivityResult,而是只对Activity调用onActivityResult。 我读过这样的东西: 如果您从片段调用startActivityForResult(),那么您应该调用startActivityForResult(),而不是getActivity().startActivityForResult(),因为这将导