How to set margin in a Textview in java source code?

Asked

Viewed 891 times

1

When I’m in the xml, only applies the property:

android:margin="15"

I want to make the application of this same property, only, in the source code of the java, how do I do that?

1 answer

2

Just set the margin on LayoutParams of View and request a new assessment of the Layout:

View view = ...

ViewGroup.LayoutParams lp = view.getLayoutParams();

if(lp instanceof ViewGroup.MarginLayoutParams) {

    ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) lp;

    lp.margin = 15;

    // Nao esqueca de requisitar o reajuste no layout
    view.requestLayout();

}
  • How do I add margin to a Textview? @Wakim

  • Everton, this code works for any View. If the margin has not applied visually, it may be some problem with the width and/or height of Textview. It would be nice to put the statement of the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.