How to set margins for TextView programmatically?
set to LayoutParams.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
tv1.setLayoutParams(params);
It depends according to your parent view.
If you using LinearLayout on your textview as a parent view give params like below
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
tv1.setLayoutParams(params);
If you using RelativeLayout on your textview as a parent view give params like below
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
tv1.setLayoutParams(params);
All these answers are great, but I was using ConstraintLayout, so here is code for that:
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 10);
textview.setLayoutParams(params); // note that textview would be your instanced TextView object