Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set margins for TextView programmatically?

People also ask

How do I set margin of TextView in android programmatically in Kotlin?

TextView tv1 = new TextView(this); tv1. setPadding(5, 0, 5, 0); tv1. setLayoutParams(new LayoutParams(LayoutParams.

How do you set margin top programmatically?

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