gpt4 book ai didi

android - 资源 $NotFoundException : resource ID not valid. 为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:35 24 4
gpt4 key购买 nike

我正在尝试向我的 dimens.xml 文件中添加一个 float 。

我正在阅读 following SO answer .当我尝试该解决方案时,我得到了评论中描述的异常。我想弄清楚为什么会抛出异常。

为了完整起见,这里是 XML:

<item name="zoom_level" format="float" type="dimen">15.0</item>

这是爆炸的代码:

final float zoom = this.getResources().getDimension(R.dimen.zoom_level);

进入Android源码,这里是getDimension的方法定义:

public float getDimension(int id) throws NotFoundException {
synchronized (mTmpValue) {
TypedValue value = mTmpValue;
getValue(id, value, true);
if (value.type == TypedValue.TYPE_DIMENSION) {
return TypedValue.complexToDimension(value.data, mMetrics);
}
throw new NotFoundException(
"Resource ID #0x" + Integer.toHexString(id) + " type #0x"
+ Integer.toHexString(value.type) + " is not valid");
}
}

因此无论出于何种原因 value.type != TypedValue.TYPE_DIMENSION。我没有完全设置我的 Android 源代码,所以我不能轻易地在其中添加 Log.w("YARIAN", "value type is "+ value.type)' 语句。

然后我跳入 getValue 调用链似乎是:

Resources.getValue -> AssetManager.getResourceValue -> AssetManager.loadResourceValue

loadResourceValue 是一种 native 方法,这就是我的挖掘失败的地方。

有人知道了解正在发生的事情的最佳方法是什么吗?


我还注意到 Resources 有一个 TypedValue.TYPE_FLOATTypedValue.TYPE_DIMENSION。但是在 XML 中,我不能写 type="float"

评论中描述的解决方法是使用 type=string,然后使用 Float.parse 获取 float 。这是必要的吗?为什么或为什么不?

最佳答案

我知道这是一个迟到的答案,但你应该使用 TypedValue#getFloat()而不是像您建议的那样将字符串解析为 float 。

XML:

    <item name="float_resource" format="float" type="raw">5.0</item>

Java:

TypedValue out = new TypedValue();
context.getResources().getValue(R.raw.float_resource, out, true);
float floatResource = out.getFloat();

如果您愿意,可以将fractionrawstring 作为type,这仅对应于R 中的资源类。

关于android - 资源 $NotFoundException : resource ID not valid. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15650384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com