I have a public class User which has a field int userID. Multiple User objects are stored in another class, SharedFlat, in an ArrayList<User>. In the Activity, I want to create and display a CheckBox for each User object in the ArrayList<User>. Since the number of Users in the ArrayList, thus also the number of CheckBoxes, is variable, I've used a for-loop and the setID()-method to set the userID of the current User object to be the ID of the corresponding CheckBox:
/* 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));
}
}
This seems to work, the CheckBoxes and corresponding userNames are correctly displayed. (Question: is there a better solution?)
Now to the real Problem: I have a Button that's supposed to check which CheckBoxes are checked (with .isChecked()), because I later have to work on with the User objects that have been "checked" at the time the onClick() method of the button was called. Since I have to get the complete User objects that have been checked, and not only their userIDs, is there a way I can get the User object by only having the Users variable userID? Would anyone have suggestion how I could solve this better? I think I found a way to find at least the userIDs of the checked User object, but I'm not quite sure if this will work out for all scenarios:
// 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);
}
}
Or if someone has a completely different solution - I "just" need to create CheckBoxes and attach IDs to them, but I don't how many CheckBoxes will be there (depends on number of users) Would be awesome if someone could help me. As you can tell, I'm quite new into programming - freshman :-) Thanks!
Aucun commentaire:
Enregistrer un commentaire