0

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?

Bob Redity
  • 529
  • 5
  • 14
  • https://stackoverflow.com/questions/1016896/how-to-get-screen-dimensions-as-pixels-in-android – Tenfour04 Feb 03 '22 at 16:17
  • @Tenfour04 I don't need to get just dimensions. I know how to get them. I need help to get % of the screen dynamically – Bob Redity Feb 03 '22 at 16:18

2 Answers2

0

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.

Luca Murra
  • 1,848
  • 14
  • 24
0

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()
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Coming in Kotlin 1.7, the last branch of a `when` with subject will have to be an `else` branch, so you'd replace that last condition with `else`. – Tenfour04 Feb 03 '22 at 16:30