我有一个GridLayout
,里面有两个或更多按钮,所有按钮的宽度必须相同。我的问题是,当按钮具有不同的文本行数时,按钮的marginTop
也会不同。我怎样才能解决这个问题?我希望所有按钮处于相同的高度位置。
感谢。
我已尝试将Gravity
设为FILL_VERTICAL
,但无效。
GridLayout grid_neighbor = (GridLayout) findViewById(R.id.grid_neighbors);
grid_neighbor.setColumnCount(4);
for (i = 0; i < namelist.length; ++i) {
Button temp = new Button(this);
temp.setText(namelist[i]);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.FILL_VERTICAL;
temp.setLayoutParams(lp);
//temp.setGravity(Gravity.FILL_VERTICAL);
temp.setWidth(button_size);
temp.setHeight(button_size);
grid_neighbor.addView(temp);
}
这是图片:
这现在也有效。
GridLayout grid_neighbor = (GridLayout) findViewById(R.id.grid_neighbors);
grid_neighbor.setColumnCount(4);
for (i = 0; i < namelist.length; ++i) {
Button temp = new Button(this);
temp.setText(namelist[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_TOP, temp.getId());
temp.setLayoutParams(lp);
//temp.setGravity(Gravity.FILL_VERTICAL);
temp.setWidth(button_size);
temp.setHeight(button_size);
grid_neighbor.addView(temp);
}
这样可行!感谢。
GridLayout.Spec speccolumn = GridLayout.spec(i%4);
GridLayout.Spec specrow = GridLayout.spec(i/4, GridLayout.TOP);
grid_neighbor.addView(temp, new GridLayout.LayoutParams(specrow, speccolumn));
答案 0 :(得分:0)
如果设置为GridLayout行的基线无法解决您的问题?因为如果网格元素中有不同数量的文本行,android会自动尝试将文本对齐到相同的基线,而不是对齐行元素。
编辑:我认为设置rowSpec.alignment = TOP(或http://developer.android.com/reference/android/widget/GridLayout.Alignment.html中可用的其中一个对齐)更合适。有关详细信息,请参阅http://developer.android.com/reference/android/widget/GridLayout.LayoutParams.html。