这是一个棘手的问题,我在表格布局中的一行中为TextView设置了margin。
看下面的代码:
TableLayout tl = new TableLayout(this);
tl.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TableRow tr = new TableRow(this);
tr.setBackgroundResource(R.color.rowColor);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(4, 4, 4, 4);
TextView tv = new TextView(this);
tv.setBackgroundResource(R.color.textviewColor);
tv.setText("hello");
tr.addView(tv, params);
TextView tv2 = new TextView(this);
tv2.setBackgroundResource(R.color.textviewColor);
tv2.setText("hi");
tr.addView(tv2, params);
tl.addView(tr);
setContentView(tl);
在表格行中使用LayoutParams所需导入的类是:
import android.widget.**TableRow**.LayoutParams;
需要注意的是我为表格行添加了class。类似地,还有许多其他可用于使用LayoutParams的类,如:
import android.widget.**RelativeLayout**.LayoutParams;
导入 android.widget.LinearLayout.LayoutParams;
之后根据需要使用即可。