android fragment如何保存狀態(tài)

小樊
120
2024-06-26 16:21:46

Android Fragment有多種方法可以保存狀態(tài),以下是一些常用的方法:

  1. 使用Bundle:在Fragment中重寫onSaveInstanceState方法,將需要保存的數(shù)據(jù)放入Bundle中,然后在onCreate方法中進(jìn)行恢復(fù)。例如:
@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");
    }
}
  1. 使用SharedPreferences:將需要保存的數(shù)據(jù)存儲(chǔ)在SharedPreferences中,在Fragment銷毀時(shí)保存數(shù)據(jù),在Fragment創(chuàng)建時(shí)讀取數(shù)據(jù)。例如:
@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", "");
}
  1. 使用ViewModel:創(chuàng)建一個(gè)ViewModel對(duì)象來(lái)保存數(shù)據(jù),在Fragment重新創(chuàng)建時(shí)獲取ViewModel對(duì)象。例如:
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
        }
    });
}

這些方法可以根據(jù)具體的需求選擇使用,以實(shí)現(xiàn)Fragment狀態(tài)的保存和恢復(fù)。

0