0
我通過在活動中重寫onSaveInstanceState
來保存對象的ArrayList
。在該活動的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;
}
}
當我旋轉屏幕,不僅對象,但也將滾動位置恢復。
- 滾動位置如何保存並恢復,即使我沒有保存它?
- 當調用
super.onCreate(savedInstanceState)
時,滾動位置是否自動保存?模擬器的
截圖之前和之後旋轉 - 旋轉
感謝您的幫助後旋轉
&之前!
看法保存自己的狀態。列表視圖保存哪個項目是第一個可見的項目。 – njzk2
@ njzk2但是,當屏幕旋轉時不重新創建活動嗎?你能否指點我一些資源,我可以閱讀有關視圖如何保存其狀態的資源? –
它被重新創建,但視圖的狀態仍然保存並自動恢復。 – njzk2