【问题标题】:how to store recyclerview data on onSaveInstanceState如何在 onSaveInstanceState 上存储 recyclerview 数据
【发布时间】:2019-07-27 08:18:27
【问题描述】:

我想将来自 API 的数据保存在 RecyclerView 中,以便在旋转屏幕时不会重新加载

我认为我可以使用 onSaveInstanceState 但仍然不太了解如何使用它

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final RecyclerView rvTVShow = view.findViewById(R.id.rv_shows);
    rvTVShow.setHasFixedSize(true);
    rvTVShow.setLayoutManager(new LinearLayoutManager(getActivity()));

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);
    Call<MovieResponse> call = apiService.getTVShow(API_KEY);
    call.enqueue(new Callback<MovieResponse>() {

        @Override
        public void onResponse(@NonNull Call<MovieResponse> call, @NonNull Response<MovieResponse> response) {
            final List<Movies> movies = Objects.requireNonNull(response.body()).getResults();

           TvShowAdapter tvShowAdapter = new TvShowAdapter(movies , R.layout.list_movies);
           rvTVShow.setAdapter(tvShowAdapter);

           ....
        }

【问题讨论】:

标签: android android-recyclerview onsaveinstancestate


【解决方案1】:

我将解释在重构代码时 savedInstanceState 的工作原理。

首先:为它创建一个全局 Movie 对象和一个 Adapter

  List<Movies> movies = new ArrayList();
  TvShowAdapter tvShowAdapter = null;

在活动onCreate下重新初始化适配器

  tvShowAdapter = new TvShowAdapter(movies , R.layout.list_movies);
       rvTVShow.setAdapter(tvShowAdapter);

创建一个新的方法来处理电影 数据人口

 public void populateRV(List<Movies> movies)
{
      this.movies = movies;
   //notify adapter about the new record
      tvShowAdapter.notifyDataSetChanged(); 
 }

将数据插入到您的 Response 回调下的 Movies 对象

  movies = Objects.requireNonNull(response.body()).getResults();
 populateRV(movies);

每次 Activity 的方向发生变化时,Android 都会通过重绘所有视图来重置它们的状态。这会导致非持久性数据丢失。但在重绘视图之前,它会调用 onSavedInstanceState

方法

因此,我们可以通过使用 android 提供的已定义的 onSavedInstanceState 方法保存视图的状态来防止状态丢失。

在您的活动的重写 onSavedInstanceState 方法中添加以下块

 //this saves the data to a temporary storage
 savedInstanceState.putParcelableArrayList("movie_data", movies);
 //call super to commit your changes
 super.onSaveInstanceState(savedInstanceState);

接下来是方向改变完成后恢复数据

在您的活动 onCreate 中添加以下块,并确保它在初始化您的适配器之后出现

 //...add the recyclerview adapter initialization block here before checking for saved data

 //Check for saved data
 if (savedInstanceState != null) {
 // Retrieve the data you saved
 movies = savedInstanceState.getParcelableArrayList("movie_data");

  //Call method to reload adapter record
 populateRV(movies);
 } else {
 //No data to retrieve
//Load your API values here.
 }

【讨论】:

  • 很好的解释。希望我知道你想要这么多解释:) 恭喜@GiddyNaya
猜你喜欢
  • 2015-03-15
  • 2010-12-19
  • 2013-02-02
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多