yar*_*ian 9 android android-resources
我想在我的dimens.xml文件中添加一个浮点数.
我正在阅读以下SO答案.当我尝试解决方案时,我得到了评论中描述的异常.我想弄清楚,为什么这会抛出异常.
为了完整性,这里是XML:
<item name="zoom_level" format="float" type="dimen">15.0</item>
Run Code Online (Sandbox Code Playgroud)
这是爆炸的代码:
final float zoom = this.getResources().getDimension(R.dimen.zoom_level);
Run Code Online (Sandbox Code Playgroud)
我跳进了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");
}
}
Run Code Online (Sandbox Code Playgroud)
无论出于何种原因value.type != TypedValue.TYPE_DIMENSION.我没有完全设置我的Android源代码,因此我无法Log.w("YARIAN", "value type is " + value.type)'在那里轻松添加语句.
然后我跳进去getValue了,调用链似乎是:
Resources.getValue -> AssetManager.getResourceValue -> AssetManager.loadResourceValue
Run Code Online (Sandbox Code Playgroud)
loadResourceValue 是一种本土方法,这是我的挖掘分崩离析的地方.
有人知道了解最新情况的最佳方法是什么?
我也注意到Resources有一个TypedValue.TYPE_FLOAT和TypedValue.TYPE_DIMENSION.但在XML中,我无法写type="float".
注释中描述的工作是使用type=string然后使用Float.parse来获取浮点数.这有必要吗?为什么或者为什么不?
Ric*_*ich 16
我知道这是一个迟到的答案,但你应该使用TypedValue#getFloat()而不是像你建议的那样将String解析为浮点数.
XML:
<item name="float_resource" format="float" type="raw">5.0</item>
Run Code Online (Sandbox Code Playgroud)
Java的:
TypedValue out = new TypedValue();
context.getResources().getValue(R.raw.float_resource, out, true);
float floatResource = out.getFloat();
Run Code Online (Sandbox Code Playgroud)
你可以把fraction,raw或者string因为type如果你喜欢,这仅相当于在资源类R.
| 归档时间: |
|
| 查看次数: |
4625 次 |
| 最近记录: |