如何在saveInstanceState中保存可选GridLayoutManaer RecyclerView的UI状态

时间:2018-09-07 21:01:16

标签: android android-recyclerview

我有一个RecyclerView,它在选定的菜单项上使用GridLayoutManager和不同的适配器。我想保存RecyclerView的最后显示项目的状态,以便用户可以在更改配置后看到相同的状态。用户界面不必回退到默认用户界面。

下面是我要保存其UI的MainActivity。

@Overrideprotected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.activity_main);
    mDb = AppDatabase.getInstance(getApplicationContext());    
    Intent intent = getIntent();
    if (intent.hasExtra("Favourite")){  
      int favouriteMovie = intent.getIntExtra("Favourite", -2);        
       if (favouriteMovie == 1) {        
           loadFavouriteMovie();        
       }    
    }    
    movies = new ArrayList<>();    
    favouriteMovies = new ArrayList<>();    
    mLoadingIndicator = findViewById(R.id.loading_indicator);    
    mImageGrid = findViewById(R.id.rv_movies);    
    layoutManager = new GridLayoutManager(getApplicationContext(), 2);    
    mImageGrid.setLayoutManager(layoutManager);    
    mImageGrid.setHasFixedSize(true);    
    mAdapter = new 
    ImageGridAdapter(this, movies);    
    mImageGrid.setAdapter(mAdapter);    
    DividerItemDecoration decoration = new 
    DividerItemDecoration(this, VERTICAL);    
    mImageGrid.addItemDecoration(decoration);    
    DividerItemDecoration decoration2 = new 
    DividerItemDecoration(this, HORIZONTAL);    
    mImageGrid.addItemDecoration(decoration2);    
    loadMoviesTask();    
    //populateMovieData();
}
    @Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {    
  super.onRestoreInstanceState(savedInstanceState);    
    if ((savedInstanceState != null) && (savedInstanceState.getParcelable(STATE_KEY) != null)){        
        listState = savedInstanceState.getParcelable(STATE_KEY);   
    }
   }
    @Overrideprotected void onSaveInstanceState(Bundle outState) {    
        super.onSaveInstanceState(outState);    
        listState = layoutManager.onSaveInstanceState();    
        outState.putParcelable(STATE_KEY, listState);
}

我知道可以通过使用密钥并将其保存在数据库中以及在onCreate上实现,可以通过使用保存的密钥查询数据库来生成RecyclerView,但是我不想在每个onCreate上查询数据库:使用onSavedInstanceState保存状态。

我已经尝试了上面的代码,但是该应用程序不仅会执行我想要的操作。

0 个答案:

没有答案