So I want to add a random number of buttons(9,16,25) to form a kind of grid, on a relative layout. I want to add the buttons programmatically at the start of the activity. For example :
1 2 3
4 5 6
7 8 9
or
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
I create an object named BOARD that contains a set of 9 TILES for example that must be arranged in a 3x3 grid
This is how I add the buttons:
buttons = new ArrayList<>();
for (int row = 0; row < board.getNoOfRows(); row ++){
for (int column = 0; column < board.getNoOfColumns() ; column ++){
// first button
if(row == 0 && column == 0){
buttons.add(addTile(board.getTile(currentButtonIndex) , null, null));
}
// next buttons on the first row
else if(row == 0) {
buttons.add(addTile(board.getTile(currentButtonIndex) , buttons.get(currentButtonIndex - 1), null));
}
// first buttons on subsequent rows
else if (row > 0 && column == 0){
buttons.add(addTile(board.getTile(currentButtonIndex) , null, buttons.get(currentButtonIndex - board.getNoOfColumns())));
}
// the rest of the buttons
else if (row > 0 && column > 0){
buttons.add(addTile(board.getTile(currentButtonIndex) , buttons.get(currentButtonIndex - 1), buttons.get(currentButtonIndex - board.getNoOfColumns())));
}
// add the buttons on the view
rlBoardView.addView(buttons.get(currentButtonIndex));
currentButtonIndex ++;
}
}
rlBoardView.setGravity(Gravity.CENTER);
This is the addTile method:
private Button addTile(Tile tileParam, Button leftButton, Button aboveButton){
Button tile = new Button(this);
tile.setId(tileParam.getIndex());
// setup buttons params
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
tile.setTextSize(15);
// if button exists on the left, add it to it's right
if(leftButton != null){
params.addRule(RelativeLayout.RIGHT_OF, leftButton.getId());
}
// if button exists above add it below it
if(aboveButton != null){
params.addRule(RelativeLayout.BELOW, aboveButton.getId());
}else{
}
tile.setLayoutParams(params);
tile.setOnClickListener(this);
tile.setText(String.valueOf(tileParam.getNumber()));
return tile;
}
The problem is that the resulting grid shows up as this:
2x2 grid 3x3 grid 4x4 grid
2 3 2 4 2 3
3 6 4 5 8 5 6 7
7 8 12 9 10 11
13 14 15
The numbering starts from 0.
I have no idea what I'm doing wrong. Some buttons are in the right places, while others are completely off. Also button 0 does not appear.