我需要显示一个问题以及我从服务器获取的选项列表。每个选项都有标题和图像,这些选项应该是可点击的。所以我创建了一个扩展到RelativeLayout的类ImageButton,每个选项都是一个ImageButton。我还创建了一个扩展到GridLayout的类ImageButtonGroup,并动态地将所有ImageButtons添加到此ImageButtonGroup。
除了ImageButtons的对齐外,它工作正常。 ImageButton的大小取决于标题文本的长度(图像对于所有选项都具有相同的大小),并且我很难将相等的单元格空间分配给网格布局中的每个ImageButton。请参阅下面的代码,我将ImageButtons添加到ImageButtonGroup:
ImageButtonGroup imageButtonGroup =
(ImageButtonGroup)
mInflater.inflate(
R.layout.button_image_response_layout, holder.richTextContainer, false);
int total = item.getMessage().getResponseOptions().size();
int col = 3;
int row = total / col;
imageButtonGroup.setColumnCount(col);
imageButtonGroup.setRowCount(row + 1);
for (int i = 0; i < total; i++) {
ResponseOption responseOption = item.getMessage().getResponseOptions().get(i);
ImageButtonView imageButtonView =
(ImageButtonView)
mInflater.inflate(
R.layout.image_button_layout, holder.richTextContainer, false);
imageButtonView.setData(
responseOption.getImage(), responseOption.getViewText(), responseOption.getValue());
GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams();
gridParam.setGravity(Gravity.CENTER);
gridParam.topMargin = 10;
gridParam.bottomMargin = 10;
gridParam.width = GridLayout.LayoutParams.WRAP_CONTENT;
gridParam.height = GridLayout.LayoutParams.WRAP_CONTENT;
imageButtonGroup.addView(imageButtonView, gridParam);
如何在网格布局中为这些按钮动态分配固定大小的单元格?
答案 0 :(得分:0)
您可以在创建GridLayoutParams时指定行和列,以便它自己处理依赖于总空间的大小的匹配:
GridLayout.LayoutParams first = new GridLayout.LayoutParams(row, col);
GridLayout.LayoutParams(GridLayout.Spec rowSpec,GridLayout.Spec columnSpec)
为此rowSpec和构造一个新的LayoutParams实例 columnSpec。
在您的具体情况下,它将类似于:
for (int i = 0; i < total; i++) {
ResponseOption responseOption = item.getMessage().getResponseOptions().get(i);
ImageButtonView imageButtonView =
(ImageButtonView)
mInflater.inflate(
R.layout.image_button_layout, holder.richTextContainer, false);
imageButtonView.setData(
responseOption.getImage(), responseOption.getViewText(), responseOption.getValue());
Spec row = GridLayout.spec(Math.round(i / 3);
Spec col = GridLayout.spec(i % 3);
GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(row, col);
gridParam.setGravity(Gravity.CENTER);
gridParam.topMargin = 10;
gridParam.bottomMargin = 10;
gridParam.width = GridLayout.LayoutParams.WRAP_CONTENT;
gridParam.height = GridLayout.LayoutParams.WRAP_CONTENT;
imageButtonGroup.addView(imageButtonView, gridParam);