Convert Dp to Px in Kotlin - This cast can never succeed

孤人 提交于 2021-01-29 07:26:32

问题


I ran into a problem while coding in Kotlin. I copy-pasted a java code sample that converts DP to Pixels, in order to place it as a parameter for setting padding programatically. I was expecting the IDE to automatically transform it all to Kotlin, however it failed in the process.

The code in Java looks like the following:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

After the translation to Kotlin:

val scale = resources.displayMetrics.density
val dpAsPixels = (sizeInDp * scale + 0.5f) as Int 

The cast as Int is marked with the error

"This cast can never succeed"

How can this be fixed?


回答1:


The error can be solved by removing the cast as Int and instead replace it with the method .toInt()

val scale = resources.displayMetrics.density
val dpAsPixels = (16.0f * scale + 0.5f).toInt()



回答2:


Why not trying it with an Extension Function such as

val Int.dp: Int get() = (this / getSystem().displayMetrics.density).toInt()

val Int.px: Int get() = (this * getSystem().displayMetrics.density).toInt()

Hope it helps ;)




回答3:


If you have value in dimens.xml

<dimen name="textSize">24dp</dimen>

Then, you can get value in pixel as Int

val value = resources.getDimensionPixelSize(R.dimen.textSize)


来源:https://stackoverflow.com/questions/54397305/convert-dp-to-px-in-kotlin-this-cast-can-never-succeed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!