TextView tv1 = new TextView(this); tv1. setPadding(5, 0, 5, 0); tv1. setLayoutParams(new LayoutParams(LayoutParams.
You should use LayoutParams to set your button margins: LayoutParams params = new LayoutParams( LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ); params.
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);
For Kotlin use following code snippet
(textView.layoutParams as ConstraintLayout.LayoutParams).apply {
marginStart=8.dpToPixels()
topMargin=8.dpToPixels()
marginEnd=8.dpToPixels()
bottomMargin=8.dpToPixels()
}
Change LayoutParams as per used layout. Thanks.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With