我正在研究Android如何处理我的应用程序的方向改变(我发现它在方向改变时重新启动了主活动。我已经看到,您可以重写该方法
protected void onSaveInstanceState(Bundle outState)要保存内容,请使用in onStart。问题是我有一个带有自定义对象的视图和一个使用自定义适配器的列表视图。所有的东西都在这些对象的ArrayList中,但是我注意到你不能把任意的对象放在这个包中!那么我如何保存状态呢?
发布于 2019-06-26 15:41:12
对于简单的数据,该活动可以使用onSaveInstanceState()方法并从onCreate()中的包中恢复其数据,但这种方法只适用于可以序列化然后反序列化的少量数据,而不适用于潜在的大量数据,如用户列表或位图。
The ViewModel class allows data to survive configuration changes such as screen rotations.
Architecture Components provides ViewModel helper class for the UI controller that is responsible for preparing data for the UI.
**Example**:如果您需要在应用程序中显示用户列表,请确保分配职责以获取用户列表并将其保存到ViewModel,而不是activity或片段,如以下示例代码所示。
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<User>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
// Create a ViewModel the first time the system calls an activity's onCreate() method.
// Re-created activities receive the same MyViewModel instance created by the first activity.
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
}
}https://stackoverflow.com/questions/3915952
复制相似问题