0

I have the following Button views

button1 = (Button) findViewById(R.id.button0);
button2 = (Button) findViewById(R.id.button1);
button3 = (Button) findViewById(R.id.button2);
button4 = (Button) findViewById(R.id.button3);
button5 = (Button) findViewById(R.id.button4);
button6 = (Button) findViewById(R.id.button5);
button7 = (Button) findViewById(R.id.button6);
button8 = (Button) findViewById(R.id.button7);

And this Button[]:

Button[] buttonViewsArray = new Button[8];

I would like to use a for loop to add the buttons into the array, but not sure how to use the i variable to then reference the correct button:

  int i;
  for (i = 0; i < buttonViewsArray.length; i++){
  String j = "button" + i;
  Button[i] = findViewById(j);
  }

I thought maybe create a String which references the correct viewID?

2
  • Internet , you can find bunch of similar or the same example,question Commented Nov 23, 2015 at 3:17
  • You can do it in one line code if you don't wana use for loop or simply use ArrayList of Buttons. Commented Nov 23, 2015 at 4:44

2 Answers 2

1

Yes, it is possible to get a resource in a loop. Here is an example from a Sudoku app I put together (the TextViews have names of the form "tv32"):

// get the text views using dynamic layout IDs
for( int row=0; row<9; row++ )
   for( int col=0; col<9; col++ )
   {
       int layoutID = getResources().getIdentifier("tv"+row+col, "id", getPackageName());
       tv[row][col] = (TextView) findViewById(layoutID);
       // set text for testing
       //tv[row][col].setText(""+row+col);
       // set up to respond to click
       tv[row][col].setOnClickListener( new CellOnClickListener(row, col) );
   }
Sign up to request clarification or add additional context in comments.

Comments

0

No, the R.id.button6 is an integer in the R file.

You will have to call findViewById for each button and save them in an array if you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.