1

I previously asked:
Is it possible to set the "Margin" and "Padding" in Android XML with just one line each.

... and according to @MikeM.'s comment, it seems like that is not possible to do with XML.

Now to the same question but with Java code instead:


Lets say you have an ImageView or a Button in an Andriod ConstraintLayout.

Is it possible to set the "Margin" & "Padding" properties just with one command each in Java code? E.g.

layoutParams.margin="15,25,20,10"
layoutParams.padding="1,2,3,4"

And in what order would the properties then come?

  • Top, Bottom, Left(Start), Right(End)?
  • Left(Start), Top, Right(End), Bottom?

1 Answer 1

3

The answer to the other question is "no" unless you write a custom ViewGroup with a custom layout attribute. In general, when all sides are specified in the Android environment, the order of side specification is "left, top, right, bottom." I don't think this is a canonical order but it is my observation.

As for changing margins in Java where lp is the layout params for a view:

lp.setMargins(left, top, right, bottom);
view.setLayoutParams(lp);

See ViewGroup.LayoutParams.

For padding you can use View.setPadding:

view.setPadding(left, top, right, bottom)

Notice that margins are managed by ViewGroups and padding is managed by Views.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.