在Kotlin中将Dp转换为Px-这种转换永远无法成功 [英] Convert Dp to Px in Kotlin - This cast can never succeed

查看:341
本文介绍了在Kotlin中将Dp转换为Px-这种转换永远无法成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中编码时遇到了一个问题.我复制粘贴了 java代码示例,该示例将DP转换为Pixel,以便将其作为参数以编程方式设置填充.我原以为IDE会自动将其全部转换为Kotlin,但是在此过程中失败了.

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.

Java 中的代码如下:

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

翻译成 Kotlin 后:

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

演员as Int被标记为错误

此强制转换永远不会成功"

"This cast can never succeed"

如何解决?

推荐答案

可以通过删除强制转换as Int并将其替换为方法.toInt()

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()

这篇关于在Kotlin中将Dp转换为Px-这种转换永远无法成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆