2015-04-19 90 views
0

這將是一個微不足道的問題,但我相當新的Android世界。 的情況是這樣的:我有顯示一些元素選擇題,GridLayoutManagerLinearLayoutManager,不知道做什麼,現在我有一個骯髒的這樣的代碼:如何恢復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(); 

回答

0

使用SharedPreferences爲了節省偏好數據。

讓我們說這是第一次用戶使用你的應用程序:

public void onCreate(...){ 
    .... 
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); 
    boolean isFirstUse = sp.getBoolean(PREF_IS_FIRST_TIME, true); 

    if(isFirstUse){ 
     final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); 
     sp.edit().putBoolean(PREF_IS_FIRST_TIME, false).apply(); 
    } 

,那麼你可以很容易地決定使用哪種LayoutManager。當然,你也可以使用SharedPreferences爲了保存用戶選擇 。這就是SharedPreferences的全部內容。您也不應該使用onRestoreInstanceState來初始化視圖。 你應該只使用它,以便提取你已經在onSavedInstanceState

+0

我無法解決保存在Bundle內部數據 –

+0

那麼你將不得不放棄更多的細節比答案( - ; – royB

+0

我更新了答案,我明白如何利用SharedPreferences。 但我怎麼知道這是否是第一次? –

相關問題