如何在 onSaveInstanceState 上存储 recyclerview 数据

how to store recyclerview data on onSaveInstanceState

我想将 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);

           ....
        }

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

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

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

在 activity 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(); 
 }

在响应回调下将数据插入电影对象

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

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

因此,我们可以使用 android.

提供的已定义的 onSavedInstanceState 方法保存我们的视图状态,从而防止状态丢失

在 activity

的重写 onSavedInstanceState 方法中添加以下块
 //this saves the data to a temporary storage
 savedInstanceState.putParcelableArrayList("movie_data", movies);
 //call super to commit your changes
 super.onSaveInstanceState(savedInstanceState);

接下来是方向转换完成后恢复数据

在您的 activity 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.
 }