This one is tricky problem, i set margin to textview in a row of a table layout. see the below:
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);
the class needed to import for LayoutParams for use in a table row is :
import android.widget.**TableRow**.LayoutParams;
important to note that i added the class for table row. similarly many other classes are available to use LayoutParams like:
import android.widget.**RelativeLayout**.LayoutParams;
import android.widget.LinearLayout.LayoutParams;
so use accordingly.