javaandroidlayoutpaddingmargin

Command and Property order for "Margin" and "Padding" in Android Java Code


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?


Solution

  • 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.