这是一个棘手的问题,我在表格布局的一行中将margin设置为textview。见下面:
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;
重要的是要注意,我为表行添加了类。类似地,还有许多其他类可用于使用LayoutParams,例如:
import android.widget.**RelativeLayout**.LayoutParams;
导入android.widget。LinearLayout .LayoutParams;
因此请相应地使用。