尝试检索维度时出错 NotFoundException

error NotFoundException while trying to retrieve dimension

很奇怪,我获取不到dimen值,怎么回事?清除缓存或使缓存无效没有帮助。

dimens.xml:

<dimen name="dialog_width_percent">0.85</dimen>

代码:

float percent = context.getResources().getDimension(R.dimen.dialog_width_percent);

得到Resources$NotFoundException

0.85 不是有效维度。使用 fraction

<fraction name="dialog_width_percent">0.85</fraction>

float percent = context.getResources().getFraction(R.fraction.dialog_width_percent, 1, 1);

尝试0.85dp如下

<dimen name="dialog_width_percent">0.85dp</dimen>

您不应该使用 float 或 double 作为资源类型,检查这个 link: Android float/double resource type

基本上它解释了如果你想使用这种类型你将不得不做一种"hack"。从原来的 post:

 <item name="float" type="dimen" format="float">9.52</item>

引用自java

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

Link 到 android 开发站点解释无法使用 float/double: https://developer.android.com/guide/topics/resources/available-resources

尺寸应 dp 改用分数。

<fraction name="dialog_width_percent" type="fraction">85%</fraction>

然后您可以在 activity 中这样调用它:

float percent = context.getFraction(R.fraction.dialog_width_percent, 1, 1);