1
什麼,我試圖做 ::我想保存數據進入的EditText和微調onorientation改變保存數據片段的方向變化
發生了什麼 :::我不能保存數據,我怎麼能解決這個
MainActivity.java
public class MainActivity extends FragmentActivity {
Fragment_A frgObj;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
Log.d("MAIN-ACTIVITY", "onCreate");
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
Log.d("MAIN-ACTIVITY", "onStart");
frgObj=Fragment_A.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.container, frgObj).addToBackStack(null).commit();
}
public void onSaveInstanceState(Bundle outState){
getSupportFragmentManager().putFragment(outState,"myfragment",frgObj);
}
public void onRetoreInstanceState(Bundle inState){
frgObj = (Fragment_A) getSupportFragmentManager().getFragment(inState,"myfragment");
}
}
Fragment_A.java
public class Fragment_A extends Fragment{
Button btn;
Spinner spinner;
EditText editText;
SeekBar seekBar;
public static Fragment_A newInstance() {
Log.d("FRAGMENT-A", "newInstance");
Fragment_A fragment = new Fragment_A();
return fragment;
}
@Override
public void onAttach(Activity activity) {
Log.d("FRAGMENT-A", "onAttach");
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onCreate");
super.onCreate(savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
Log.d("FRAGMENT-A", "onSaveInstanceState");
super.onSaveInstanceState(outState);
//City Spinner state
outState.putString("editText", editText.getText().toString());
outState.putInt("yourSpinner", spinner.getSelectedItemPosition());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onCreateView");
View view=inflater.inflate(R.layout.fragment_a, container, false);
btn=(Button) view.findViewById(R.id.buttonId1);
spinner=(Spinner) view.findViewById(R.id.spinnerId1);
editText=(EditText) view.findViewById(R.id.editTextId1);
seekBar=(SeekBar) view.findViewById(R.id.seekBarId1);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onActivityCreated");
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//City Spinner state
editText.setText(savedInstanceState.getString("editText"));
spinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
}
}
@Override
public void onStart() {
Log.d("FRAGMENT-A", "onStart");
super.onStart();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("FRAGMENT-A", "button Clicked");
Fragment_B frgObj=Fragment_B.newInstance();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, frgObj,"Fragment_B").addToBackStack(null).commit();
}
});
}
}
在你的MainActivity中刪除onSaveInstanceState和onRetoreInstanceState –
@Rod_Algonquin ....我認爲這是必要的權利.....(我引用此棧發佈http://stackoverflow.com/a/15914053/1083093) – Devrath