Good day! There was a need to process twelve buttons in one fragment (calculator). For convenience, I would like to keep all these buttons in the collection.

buttons = new ArrayList<>(); buttons.add(0, (Button) v.findViewById(R.id.button_0)); buttons.add(1, (Button) v.findViewById(R.id.button_1)); buttons.add(2, (Button) v.findViewById(R.id.button_2)); buttons.add(3, (Button) v.findViewById(R.id.button_3)); buttons.add(4, (Button) v.findViewById(R.id.button_4)); buttons.add(5, (Button) v.findViewById(R.id.button_5)); buttons.add(6, (Button) v.findViewById(R.id.button_6)); buttons.add(7, (Button) v.findViewById(R.id.button_7)); buttons.add(8, (Button) v.findViewById(R.id.button_8)); buttons.add(9, (Button) v.findViewById(R.id.button_9)); 

etc. Is it possible to somehow do this in a loop? Thank you in advance.

  • you can add, but you still need to have a list of their ID students R.id.button ... - Kirill Stoianov
  • one
    You can programmatically create and add buttons - Vladyslav Matviienko

1 answer 1

If I understand you correctly, you need to do this:

 for (int i = 1; i <= 12; i++) { int id = getResources().getIdentifier("button_".concat(String.valueOf(i)), "id", getActivity().getPackageName()); buttons.add((Button) view.findViewById(id)); }