2017-02-16 17 views
0

有幾個動態充氣/添加複選框,當一些被選中時旋轉或最小化應用程序(爲了便於觸發該情況,打開'不保持活動活着'),恢復的UI視圖顯示所有選中的複選框。爲什麼checkBox是在setChecked(false)被調用時檢查的

當os執行saveInstance時,我們將檢查的項目存儲在一個列表中,當操作系統恢復片段時,我們得到檢查項目的列表,並且當重新填充複選框行時,它會調用setChecked(true)或setChecked假)基於列表。 但之後,所有的複選框顯示爲選中狀態,雖然在調試中它清楚地顯示只有選中的選項被使用'true',而其他選項使用setChecked()選項'false'。

任何人都會遇到同樣的情況,或者知道爲什麼單個checkBox實例上的setChecked()不會執行所謂的調用?

itemList中= [A,B,C,d,E]

checkedListSet = [A,B]

void insertOneRow(ViewGroup container, Item item) { 

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View itemLayout = inflater.inflate(R.layout.item_row, null, false); 

    TextView txt = (TextView)itemLayout.findViewById(R.id.text); 
    txt.setText(item.toString());   
    container.addView(itemLayout, container.getChildCount()); 

    CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkbox); 
    if (checkbox != null) { 
     boolean isChecked = (checkedListSet.get(item) != null); 

     Log.i(「insertOneRow(), isChecked:"+ isChecked +", item:」+item); 

     checkbox.setChecked(isChecked); //<== trace shows only A and B are set with true 
    } 
} 

item_row.xml

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="36dp" 
    android:orientation="horizontal" 
> 

    <CheckBox 
     android:id="@+id/checkbox" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:checked="false"   /> 

    <TextView 
     android:id="@+id/text" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="1"    
    /> 

</LinearLayout> 
+0

是什麼類型'checkedListSet'對象?我認爲在列表上獲取方法只接受一個int作爲索引。 –

+0

checkedList只是一個包含檢查項的列表,可能是ListArray 或HashSet ,checkedListSet.get(item)!= null只是想說如果該項存在於checkList中,那麼checkBox需要設置爲true。 – lannyf

回答

0
checkedListSet.get(item) != null 

此方法如果列表中有一個項目並且它不爲null,則返回true。

您正在將此表達式的結果分配給您的isChecked布爾值。

因此,每當此表達式返回true時,您的複選框將爲setChecked true。

我不知道在設置複選框之前要檢查什麼確切的條件,所以我不能幫你。

+0

看到我上面的評論。它不是真正的運行代碼,它只是試圖說明該項目是否在checkedList中,然後checkBox將被設置爲true。 – lannyf

0

仍然不確定爲什麼,但放在android:saveEnabled =「false」後,相同的代碼開始工作。有誰知道爲什麼它必須有android:saveEnabled =「false」?

<CheckBox 
     android:saveEnabled="false" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     /> 
0

所有的複選框都被檢查的原因是他們都有相同的id。如果他們中的任何一個被選中並且他們被重新創建(無論是因爲方向改變還是重新連接片段),Android系統會嘗試恢復他們的狀態,並根據他們的ID識別它們。因此他們都被檢查。這是Android中的一個錯誤。

android:saveEnabled標誌告訴Android系統是否保存它們的狀態並嘗試稍後恢復。

既然你已經有一個機制來恢復他們的狀態設置android:saveEnabled虛假爲你工作。

看到這個問題,通過這種類似的事情發生與EditTextWhy does Android change the value of EditTexts with same id?

相關問題