How to Change Margin of TextView

Solution 1:

TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);     
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);

I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.

Solution 2:

Your layout in xml probably already has a layout_margin(Left|Right|etc) attribute in it, which means you need to access the object generated by that xml and modify it.

I found this solution to be very simple:

ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mTextView
        .getLayoutParams();

mlp.setMargins(adjustmentPxs, 0, 0, 0);

break;

Get the LayoutParams instance of your textview, downcast it to MarginLayoutParams, and use the setMargins method to set the margins.

Solution 3:

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.

Solution 4:

setMargins() sets the INNER margins of the TextView, not the layout-margins. Is that what you want to do? This two different margins can be quite complicated.

If you want to set the layout margins, change the LayoutParams of the TextView (textview.getLayoutParams(), then change the parameters on the returned LayoutParams object).

You don't need to change anything on your LinearLayout.

Regards, Oliver

Solution 5:

TextView does not support setMargins. Android docs say:

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.