Android: Setting a button size programatically

1.1k views Asked by At

I'm trying to make a 100x100 px button and add it to a gridlayout on the position 3,3

Button btn = new Button(this);
btn.setLayoutParams(new ViewGroup.LayoutParams(100,100));
GridLayout grid4x4 = (GridLayout)findViewById(R.id.grid4x4);

//I've narrowed it down to the conclusion that this line is the problem:
grid4x4.addView(btn,new GridLayout.LayoutParams(GridLayout.spec(3),GridLayout.spec(3)));
//if i just use:
//grid4x4.addView(btn); I get the button the size I want it, but I need it to be on 
//the 3,3 position of the grid.

This "almost" works, excepting the fact that the button added is bigger than 100x100px as you can see I'm trying to fix the size I want yet for some reason that's not the size I get.

2

There are 2 answers

0
Artemio Ramirez On BEST ANSWER

This might not be the ideal solution, but this worked exactly the way I wanted:

Button btn = new Button(this);
btn.setLayoutParams(new ViewGroup.LayoutParams(100,100));
GridLayout grid4x4 = (GridLayout)findViewById(R.id.grid4x4);
grid4x4.addView(btn);
((GridLayout.LayoutParams) btn.getLayoutParams()).rowSpec = GridLayout.spec(3);
((GridLayout.LayoutParams) btn.getLayoutParams()).columnSpec = GridLayout.spec(3);

Oim~

2
Rami On

in your res/values/dimens.xml add <dimen name="mybuttonsize">100px</dimen>

int size = (int) getResources().getDimension(R.dimen.mybuttonsize);

change your code to:

btn.setMaxWidth(size);
btn.setMaxHeight(size);
btn.setLayoutParams(new ViewGroup.LayoutParams(size,size));