在改变安卓系统活动时保持ArrayList的值,可以使用以下方法:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("list", arrayList);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
arrayList = (ArrayList<String>) savedInstanceState.getSerializable("list");
}
}
// 保存ArrayList到SharedPreferences
SharedPreferences sharedPrefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
Set<String> set = new HashSet<>(arrayList);
editor.putStringSet("list", set);
editor.apply();
// 从SharedPreferences中恢复ArrayList
Set<String> set = sharedPrefs.getStringSet("list", null);
if (set != null) {
arrayList = new ArrayList<>(set);
}
首先,在build.gradle文件中添加以下依赖:
implementation "androidx.lifecycle:lifecycle-viewmodel:2.4.0"
然后,创建一个继承自ViewModel的类,在该类中定义一个ArrayList变量,并提供相应的getter和setter方法。
public class MyViewModel extends ViewModel {
private ArrayList<String> arrayList;
public void setArrayList(ArrayList<String> arrayList) {
this.arrayList = arrayList;
}
public ArrayList<String> getArrayList() {
return arrayList;
}
}
在Activity中使用ViewModel:
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
if (savedInstanceState != null) {
ArrayList<String> savedArrayList = savedInstanceState.getStringArrayList("list");
viewModel.setArrayList(savedArrayList);
}
// 使用viewModel.getArrayList()获取ArrayList实例
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("list", viewModel.getArrayList());
}
通过以上方法,可以在改变安卓系统活动时保持ArrayList的值,并且不涉及到特定的云计算品牌商。
领取专属 10元无门槛券
手把手带您无忧上云