Android Fragment有多种方法可以保存状态,以下是一些常用的方法:
- 使用Bundle:在Fragment中重写onSaveInstanceState方法,将需要保存的数据放入Bundle中,然后在onCreate方法中进行恢复。例如:
@Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("key", value); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { value = https://www.yisu.com/ask/savedInstanceState.getString("key"); } }
- 使用SharedPreferences:将需要保存的数据存储在SharedPreferences中,在Fragment销毁时保存数据,在Fragment创建时读取数据。例如:
@Override public void onDestroy() { super.onDestroy(); SharedPreferences preferences = getActivity().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("key", value); editor.apply(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = getActivity().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); value = https://www.yisu.com/ask/preferences.getString("key", ""); }
- 使用ViewModel:创建一个ViewModel对象来保存数据,在Fragment重新创建时获取ViewModel对象。例如:
public class MyViewModel extends ViewModel { private MutableLiveDatadata = https://www.yisu.com/ask/new MutableLiveData<>(); public LiveData getData() { return data; } public void setData(String value) { data.setValue(value); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class); viewModel.getData().observe(this, new Observer () { @Override public void onChanged(String value) { // Update UI with the new value } }); }
这些方法可以根据具体的需求选择使用,以实现Fragment状态的保存和恢复。