我有一個public class User
它有一個字段int userID
。多個User
對象存儲在另一個類中,SharedFlat
,存儲在ArrayList<User>
中。在活動中,我想爲ArrayList<User>
中的每個User
對象創建並顯示CheckBox。由於ArrayList中的用戶數量(也就是CheckBox的數量)是可變的,因此我使用了for循環和setID()
-方法將當前User對象的userID
設置爲相應CheckBox的ID:從可變長度/字段的數組中獲取ID到類?
/* This method displays the CheckBoxes with the user names to the R.layout.new_payment_screen layout file */
private void createCheckboxes(SharedFlat flat) {
// Find the layout and create a Checkbox Array to store all users
LinearLayout ll = (LinearLayout) findViewById(R.id.who_received);
final CheckBox[] checkBoxes = new CheckBox[flat.getNumberOfUsers()];
// Create a new Checkbox for each user and set the users name to it
for (int i = 0; i < checkBoxes.length; i++) {
// create new checkboxes
checkBoxes[i] = new CheckBox(this);
// add checkboxes to the layout
ll.addView(checkBoxes[i]);
// set text of the CheckBox to be userName of current User object
checkBoxes[i].setText(flat.getSpecificUserName(i));
// set the ID to be the userID of the corresponding User
checkBoxes[i].setId(flat.getSpecificUserID(i));
}
}
這似乎工作,CheckBoxes和相應的用戶名正確顯示。 (問:有沒有更好的解決辦法嗎?)
我們真正的問題:我有一個是應該檢查檢查其的CheckBox(與.isChecked()
)按鈕,因爲我後來有一個包含了該User
對象上下工夫在調用按鈕的onClick()
方法時已被「檢查」。 因爲我必須得到完整的User
已檢查的對象,而不僅僅是它們的userID
,有沒有辦法通過User
的變量userID
來得到User
對象?有人會建議我如何能更好地解決這個問題嗎? 我想我找到了一種方法找到的檢查User
對象的至少userIDs
,但我不能肯定這是否會制定出對所有情景:
// Find the CheckBoxes within the LinearLayout and search them for the checked ones (= Receivers)
LinearLayout ll = (LinearLayout) findViewById(R.id.who_received);
final int checkBoxCount = ll.getChildCount();
ArrayList<Integer> userIdList = new ArrayList<Integer>();
for (int i = 0; i < checkBoxCount; i++) {
CheckBox currentCheckBox = (CheckBox) ll.getChildAt(i);
if (currentCheckBox.isChecked()) {
userIdList.add(i);
}
}
或者,如果有人有一個完全不同的解決方案 - 我「只是」需要創建複選框並將ID附加到它們,但我不會有多少複選框將在那裏(取決於users
的數量) 如果有人可以幫助我,那將會很棒。正如你所看到的,我對編程頗爲陌生 - 新生:-) 謝謝!
真棒,它的作品!用'setTag'和'getTag'方法的好主意,我還不知道。非常感謝你的幫助!! –
P.S .:你的幫助爲我節省了15-20行代碼,包括一個非常臨時,混亂的方法。再次感謝,很棒的工作! :-) –