2014-10-02 64 views
0

在我的應用程序中,我使用文件中的隨機數據填充GridView的適配器。數據以每個項目的TextView形式顯示給用戶。如果用戶觸摸某個項目,該項目會更改背景顏色。旋轉後保持視圖狀態/方面

的問題是,如果用戶觸摸的項目,然後旋轉該裝置,該項目返回到其原始方面(與正常背景顏色)

我已經嘗試不同的方法:

  • 實現我自己的適配器
  • 擴大BaseAdapter
  • 使用ArrayAdapter
  • 使用選擇的TextView的
  • 擴展與自定義樣式TextView的項目(從herehere
  • 禁用內查看GridView的onItemClick(AdapterView<?> parent, View view, int position, long id)

我想要做的就是保持意見顏色/風格/一個方面,當我旋轉設備

注意

爲什麼我從文件加載radomly數據?

該文件包含不同的詞。每次玩家開始活動(這是一場遊戲),GridView內部會顯示隨機順序的不同單詞。用戶需要指出正確的單詞。如果用戶犯了一個錯誤,單詞會改變顏色(的確,我更喜歡禁用視圖)。重複該過程直到用戶做出正確的選擇。

回答

0

您可以保存的onSaveInstanceState使用列表的選擇的狀態。

當你點擊你的列表中,您可以在狀態分配給布爾數組中的項。

實現您的片段/活動的方法的onSaveInstanceState。

public void onSaveInstanceState(Bundle outState) { 

    super.onSaveInstanceState(outState); 
    outState.putBooleanArray(BundleArgs.STATES, mAdapter.getStates()); 

}

然後在onCreateView傳遞這些值到您的適配器。

if (savedInstanceState != null) { 
    states = savedInstanceState.getBooleanArray(BundleArgs.STATES); 
    //Declare adapter and pass states to it 
    myAdapter = new Adapter(context, values, states); 
} 
0

這是一個我在SO上看過幾次的錯誤。

dataview代表的數據是完全不同實體,他們應該分開處理。

你需要保持你的數據的狀態,另一個數據元素和旋轉過程中保留該數據元素。例如(這只是一個例子,」做這件事的幾種方法):

// possible states 
private static final int NORMAL = 0; 
private static final int RIGHT = 1; 
private static final int WRONG = 2; 
Map<String, Integer> states; // here you keep the states 

然後在每一次點擊,對檢查答案,並改變顏色代碼:

// process the click/state change 
states.put(word, newState); 

然後旋轉:

public void onSaveInstanceState(Bundle outState) { 
    outState.putSerializable("states", states); 
} 

和創建

// onCreate 
if (savedInstanceState != null) { 
    states = (Map<String, Integer>) savedInstanceState.getSerializable("states"); 
} else { 
    states = new HashMap<String, Integer>(); 
} 

然後回到自定義適配器上,您必須檢查狀態並相應地修改視圖。

// inside getView 
int state = 0 
if(states.containsKey(word)){ 
    state = states.get(word).intValue(); 
} 
switch(state){ 
    // deal with the cases and set the color 
} 
+0

在我看來,改變TextView狀態並不是一樣的數據和視圖。這是你提到的錯誤嗎? – Manuel 2014-10-03 12:33:06

+0

錯誤在於使用'View's作爲數據的主要參考。這是因爲View被破壞,重建和回收,特別是在處理ListView時。因此,您需要一個完全獨立的實體來存儲數據,並相應地設置視圖狀態。 – Budius 2014-10-03 12:40:54

+0

但是我沒有使用'View'作爲數據的參考,是嗎? – Manuel 2014-10-03 13:12:59