0

We know that to set margins this is one way of doing it

I discovered this example from this answer. it sets margins in the dp unit type.

val param = xml.layoutParams as ViewGroup.MarginLayoutParams
    
param.setMargins(left, top, right, bottom)
    
xml.layoutParams = param

This variable i discovered from this answer. It translates pixels to dp allowing you to then use it for one of the parameters shown in my previous example.

val pxToDP = if ( direction == "left" || direction == "right" ) {
                px / ( xml.context.resources.displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)
            } else if ( direction == "top" || direction == "bottom" ) {
                px / ( xml.context.resources.displayMetrics.ydpi / DisplayMetrics.DENSITY_DEFAULT)
            }

But what if i want to set margin using a variable that represent inches? How would i do that?

And are there any other methods i can use to set margin in Kotlin where the variable represents a different unit type? If so, what are the methods?

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
Jevon
  • 295
  • 2
  • 13

1 Answers1

0

most often case in Android when setting any dimensions: pixels are used. also setMargins get px values, not dps or any other (according to doc). so if you have some number in different unit then you need to convert it to pixels

for re-calculating some value in given unit use TypedValue class, e.g. like below:

int _10dpInPixelUnit = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
            getResources().getDisplayMetrics());

if you want to use inches just use TypedValue.COMPLEX_UNIT_IN (some doc and other units HERE)

snachmsm
  • 17,866
  • 3
  • 32
  • 74