请查看以下代码
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class InputFragment extends Fragment {
private SeekBar daysAsCustomerSeek;
private View view;
//Following variables will save the application state and load back
//on resume
private final String DAYS_AS_CUSTOMER_VALUE_HOLDER = "days as customer value";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Intializing instance variables
view = inflater.inflate(R.layout.input, container,false);
daysAsCustomerSeek = (SeekBar)view.findViewById(R.id.days_as_customer_seekbar);
//Set default max values
daysAsCustomerSeek.setMax(210);
return view;
}
//This method will save the instances
@Override
public void onSaveInstanceState(Bundle savedInstanceStateBundle)
{
savedInstanceStateBundle.putInt(DAYS_AS_CUSTOMER_VALUE_HOLDER, daysAsCustomerSeek.getProgress());
}
//This method will restore the instances
@Override
public void onActivityCreated(Bundle savedInstanceStateBundle)
{
super.onActivityCreated(savedInstanceStateBundle);
if(savedInstanceStateBundle!=null)
{
daysAsCustomerSeek.setProgress(savedInstanceStateBundle.getInt(DAYS_AS_CUSTOMER_VALUE_HOLDER));
}
}
}
问题是当我转动设备或导航回到这个片段时,其状态未被保存!相反,一切都被重建了!为什么是这样?为什么这段代码没有显示状态?
答案 0 :(得分:2)
添加:
super.onSaveInstanceState(savedInstanceStateBundle);
在onSaveInstanceState
方法中。
答案 1 :(得分:0)
someFragment.setRetainInstance(true);