0

我收到了我的应用程序的第一份崩溃报告。它说有一个java.lang.ArithmeticException: divide by zero

例外是在这两行之一:

//sWP stands for "Screen Width in Pixels"
// sW stands for "Screen Width" The code is old though, so I may be incorrect for both variables.
//res is just getResources()
int sWP = sW / (res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
float bHeight = 50 * ((float)res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);

可以DisplayMetrics.DENSITY_DEFAULT为零吗?或者getDisplayMetrics().densityDpi永远为零?

4

1 回答 1

0

res.getDisplayMetrics().densityDpi将是 120、160 或 240(或类似的),请参阅https://developer.android.com/reference/android/util/DisplayMetrics.html#densityDpi

DisplayMetrics.DENSITY_DEFAULT始终等于 160,请参阅https://developer.android.com/reference/android/util/DisplayMetrics.html#DENSITY_DEFAULT

res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT将返回 0,因为您将 int 除以 int。

将两行中的第一行更改为

int sWP = (int) sW / (((double) res.getDisplayMetrics().densityDpi) / DisplayMetrics.DENSITY_DEFAULT);

它应该可以工作。

于 2016-10-01T19:48:22.123 回答