我创造了很多图像按钮的这样的代码:编程设置ImageButton的利润率
TableRow tr = new TableRow(this);
if (db != null) {
if (db.moveToFirst()) {
do {
ImageButton button = new ImageButton(this);
int ID = Integer.parseInt(db.getString(db.getColumnIndex("ID")));
int resource = getResources().getIdentifier("unit" + ID, "drawable", getPackageName());
System.out.println("unit" + ID + ":" + resource);
button.setImageResource(resource);
button.setOnClickListener(MainActivity.this);
tr.addView(button);
button.getLayoutParams().height = 250;
button.getLayoutParams().width = 250;
button.setScaleType(ImageView.ScaleType.FIT_CENTER);
//button.setLayoutParams(tableRowParams);
rowcount++;
if (rowcount % 5 == 0) {
layout.addView(tr);
tr = new TableRow(this);
}
} while (db.moveToNext());
}
}
而且我发现代码:
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 0, 0, 0);
,并在做,而在按钮适用。
button.setLayoutParams(tableRowParams);
它会显示错误消息 “android.widget.TableLayout $的LayoutParams不能转换到android.widget.TableRow $的LayoutParams”
可能重复[在代码中动态设置边距-Android](http://stackoverflow.com/questions/12826067/setting-margins-dynamically-in-code-android) –