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狀態的保存和恢復。