Home > Mobile >  How to calculate percent of width programmatically Android?
How to calculate percent of width programmatically Android?

Time:02-04

For example I got a screen width 1000 . And I need to calculate the value of the first 25% which will be when x in 0..250 -> doSmth() and last part

which will be when x in 750..1000 -> doSmth()

But I need to make it dynamically depends on the screen width. What is the way to do that in Android?

CodePudding user response:

Once you have the width, let's say w is the width value, it's 25% is

w / 100 * 25

I don't know if this is your question.

CodePudding user response:

Divide by the width using float values to avoid integer division truncating the result to 0. Then compare to fractions of 1 instead of integer percentages.

when (x.toFloat() / screenWidth) { 
    in 0f..0.25f -> doSmth()
    in 0.75f..1f -> doSmthElse()
}
  •  Tags:  
  • Related