這將是一個微不足道的問題,但我相當新的Android世界。 的情況是這樣的:我有顯示一些元素選擇題,GridLayoutManager和LinearLayoutManager,不知道做什麼,現在我有一個骯髒的這樣的代碼:如何恢復RecyclerView的LayoutManager?
在onOptionItemSelected的代碼片段; 下面,我必須創建LinearLayoutManager的和GridLayoutManager的對象,然後設置RecyclerView
case R.id.visualizza:{
// isList() return true only if getLayoutManager() == LinearLayoutManager
if(isList()){
// setta il titolo del menu item con la stringa txtList
item.setTitle(getString(R.string.txtList));
mGridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
}else{
item.setTitle(getString(R.string.txtGrid));
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
}
break;
}
在這裏,在onRestoreInstanceState()的佈局;在這裏,我必須爲Linear和Grid創建一個對象...這個我認爲是不是一個好的練習! 但我不知道如何解決。
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.getBoolean("seiList")){
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
}else{
mGridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
}
}
我想要什麼,是什麼,如果是正在使用的應用程序,而對於其餘部分,僅保留用戶的選擇在第一時間提供的LinearLayout的設置。
我希望我已經順利通過了我的問題和那個人很樂意提供幫助!
UPDATE
我通過SharedPreferences解決了做檢查的onStop()
if (isList()){
preferences.edit().putBoolean("linear", true).commit();
我無法解決保存在
Bundle
內部數據 –那麼你將不得不放棄更多的細節比答案( - ; – royB
我更新了答案,我明白如何利用SharedPreferences。 但我怎麼知道這是否是第一次? –