Android Fragment有多种方法可以保存状态,以下是一些常用的方法:
@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 = savedInstanceState.getString("key");
}
}
@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 = preferences.getString("key", "");
}
public class MyViewModel extends ViewModel {
private MutableLiveData<String> data = new MutableLiveData<>();
public LiveData<String> 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<String>() {
@Override
public void onChanged(String value) {
// Update UI with the new value
}
});
}
这些方法可以根据具体的需求选择使用,以实现Fragment状态的保存和恢复。