我有一组按钮,这些按钮根据从SQLite数据库中提取的项目数生成。按钮生成并正常工作,但它们居中对齐并均匀分布。意思是否有一个:按钮居中;如果有两个:它们从中心均匀分布;等
我需要的是让他们保持左对齐并允许我使用边距将它们分开。我知道如何使用参数设置边距,但无法弄清楚为什么它们是在TableLayout行中居中的默认值。
除了对齐之外,代码再次起作用并完美响应。我在其他活动上遇到类似的问题,我确信它是相关的。
我已经包含了一些可能显示我正在做的事情的代码:
imgTitleTable = (TableLayout) findViewById(R.id.imagesTableLayout);
int i = 0;
while (i < imgTitle.length) {
if (i % 6 == 0) {
tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
imgTitleTable.addView(tr);
imgtr = new TableRow(this);
imgtr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
imgTitleTable.addView(imgtr);
}
// add images
ImageButton imgButton = new ImageButton(this);
imgButton.setImageResource(R.drawable.images_sample);
imgButton.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
imgButton.setBackground(null);
imgButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent theIntent = new Intent(getApplicationContext(),
Viewer.class);
startActivity(theIntent);
}
});
// add img title
TextView title = new TextView(this);
title.setText(imgTitle[i]);
title.setId(i);
title.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1f));
title.setGravity(Gravity.CENTER);
title.setWidth(imgButton.getDrawable().getIntrinsicWidth());
title.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent theIntent = new Intent(getApplicationContext(),
Viewer.class);
startActivity(theIntent);
}
});
tr.addView(imgButton);
imgtr.addView(title);
i++;
}
答案 0 :(得分:0)
尝试
TableRow.LayoutParams params = new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
params.gravity=Gravity.LEFT;
imgButton.setLayoutParams(params);