我通过覆盖活动中的ArrayList
来保存onSaveInstanceState
个对象。在该活动的onCreate
方法中,我恢复了我保存的对象列表。
以下是活动的代码 -
public class MovieListActivity extends AppCompatActivity {
private EndlessRecyclerViewScrollListener scrollListener;
private ArrayList<Movie> movies;
private MovieListAdapter movieListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
RecyclerView moviesRecyclerView = (RecyclerView) findViewById(R.id.movie_list_rv);
if (savedInstanceState == null || !savedInstanceState.containsKey("movieList")) {
movies = createMovies(30);
} else {
// Restoring only the list of movies not the scroll position
movies = savedInstanceState.getParcelableArrayList("movieList");
}
movieListAdapter = new MovieListAdapter(this, movies);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
moviesRecyclerView.setAdapter(movieListAdapter);
moviesRecyclerView.setLayoutManager(layoutManager);
scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) {
@Override
public void onLoadMore(int page, final int totalItemsCount, RecyclerView view) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
movies.addAll(createMovies(20));
movieListAdapter.notifyItemRangeInserted(totalItemsCount, movies.size() - 1);
}
};
handler.post(r);
}
};
moviesRecyclerView.addOnScrollListener(scrollListener);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Saving only the list of movies
outState.putParcelableArrayList("movieList", movies);
super.onSaveInstanceState(outState);
}
private ArrayList<Movie> createMovies(int numberOfMovies) {
ArrayList<Movie> movieList = new ArrayList<>();
for(int i=0; i<numberOfMovies; i++) {
movieList.add(new Movie("Hello", new DateTime("2017-03-16T01:20"), "This is a very good movie"));
}
Log.i("Create", "create called");
return movieList;
}
}
当我旋转屏幕时,不仅会恢复对象,还会恢复滚动位置。
答案 0 :(得分:0)
当您的活动开始停止时,系统会调用onSaveInstanceState()方法,以便您的活动可以使用一组键值对保存状态信息。此方法的默认实现保存有关活动视图层次结构状态的瞬态信息,例如EditText小部件中的文本或ListView小部件的滚动位置
有关详细信息,请参阅https://developer.android.com/guide/components/activities/activity-lifecycle.html
中的保存和恢复活动状态