我創造了很多圖像按鈕的這樣的代碼:編程設置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) –