如果没有在后台堆栈中添加片段,如何在视图寻呼机中恢复片段的状态?

时间:2016-11-07 19:16:21

标签: android android-fragments

我有activity Aactivity B。在我的清单文件中,我已将其启动模式设置为单个任务,以仅维护每个活动的一个实例。在这两个活动中,我使用了ViewPager的三个片段。现在,问题在于,当我填充activity A的所有片段的所有字段时,然后移至activity B,然后移除activity A片段中填充的数据。那么,我们如何才能恢复碎片的状态呢?

//Global Declaration
Intent i =null;

//method i used in fragment to save the value of fields.

@Override
        public void onStop() {
            super.onStop();
                i.putExtra("customerId", _customerId);
                i.putExtra("panCardName", _panCardName);
                i.putExtra("panCardAcknowledgementNmber", _panCardAcknowledgementNmber);
                i.putExtra("natureOfBusiness", _natureOfBusiness);
                i.putExtra("annualTurnover", _annualTurnover);
                i.putExtra("networth", _networth);
                i.putExtra("occupation", _occupation);
                i.putExtra("date", _date);
}

//method in fragment, where i retrieve the saved values.

 public void onResume() {
        super.onResume();
        i = getActivity().getIntent();
        if(i != null) {
            _customerId = i.getStringExtra("customerId");
            _panCardName = i.getStringExtra("panCardName");
            _panCardAcknowledgementNmber = i.getStringExtra("panCardAcknowledgementNmber");
            _natureOfBusiness = i.getStringExtra("natureOfBusiness");
            _annualTurnover = i.getStringExtra("annualTurnover");
            _networth = i.getStringExtra("networth");

_occupation = i.getStringExtra("occupation");
            _date = i.getStringExtra("date");
        }

1 个答案:

答案 0 :(得分:0)

首先你必须使用

int counter  = 0;
@Override
public void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  outState.putInt("value",counter);
}

用于保存片段中的值,

并保留以下代码中的数据,

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setRetainInstance(true);        
}

和onCreateView()方法

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,    Bundle savedInstanceState) {
   if (savedInstanceState != null) {
          int count = savedInstanceState.getInt("value");
          Toast.makeText(this, String.valueOf(count) ,    Toast.LENGTH_LONG).show();
     }
}