我试图制作一个100x100像素的按钮并将其添加到位置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.
这"几乎"除了添加的按钮大于100x100px这一事实外,你可以看到我试图修正我想要的尺寸,但由于某种原因,这不是我得到的尺寸。
答案 0 :(得分:0)
res/values/dimens.xml
添加<dimen name="mybuttonsize">100px</dimen>
中
int size = (int) getResources().getDimension(R.dimen.mybuttonsize);
将您的代码更改为:
btn.setMaxWidth(size);
btn.setMaxHeight(size);
btn.setLayoutParams(new ViewGroup.LayoutParams(size,size));
答案 1 :(得分:0)
这可能不是理想的解决方案,但这完全符合我的要求:
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〜