2017-03-16 76 views
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; 
} 

}

當我旋轉屏幕,不僅對象,但也將滾動位置恢復。

  1. 滾動位置如何保存並恢復,即使我沒有保存它?
  2. 當調用super.onCreate(savedInstanceState)時,滾動位置是否自動保存?模擬器的

截圖之前和之後旋轉 - 旋轉

enter image description here

感謝您的幫助後旋轉

enter image description here

&之前!

+0

看法保存自己的狀態。列表視圖保存哪個項目是第一個可見的項目。 – njzk2

+0

@ njzk2但是,當屏幕旋轉時不重新創建活動嗎?你能否指點我一些資源,我可以閱讀有關視圖如何保存其狀態的資源? –

+0

它被重新創建,但視圖的狀態仍然保存並自動恢復。 – njzk2

回答

0

當你的活動開始,停止,系統調用的onSaveInstanceState()方法,因此您的活動可以保存狀態信息與鍵值對的集合。此方法的默認實現保存有關活動的視圖層次,狀態瞬時信息,例如在一個EditText插件的文本或瞭解更多信息,請參閱保存一個ListView控件

的滾動位置和恢復活動狀態https://developer.android.com/guide/components/activities/activity-lifecycle.html