Given an application where there are many identical view and button ,

enter image description here

where each button + each view has its own unique id . For example, plus1 for the first, plus2 for the second, etc. How can I get all the elements in the code at once, so as not to write separately for each button an ImageButton plus1 = findViewById(R.id.plus1); ?

    1 answer 1

    For example:

     Resources res = getResources(); myButtons = new ArrayList(); for (int i = 0; i < NUMBER_OF_VIEWS; i++) { myButtons.add((ImageButton)findViewById(res.getIdentifier("plus"+ String.valueOf(i+1), "id", getPackageName()))); } 

    I don’t know the logic of the application, but it seems to me that for convenience it’s better to MyView view + button to a separate MyView class (for example) and work with ArrayList<MyView> : .getView() , .getButton() , etc.

    • In general, I need to get these advantages in order to hang listeners on them that increase the field with numbers that is on the left. I think with your example I will succeed. - Dmitry
    • one
      @Dmitry It seems easier for your task to use a RecyclerView with a base view as an item and with an ArrayList custom class. - Jarvis_J