2013-03-27 133 views
4

我想添加一個浮點數到我的dimens.xml文件。

我讀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是一個本地方法,這裏是我的地方挖分崩離析。

任何人都知道什麼是最好的方式來理解發生了什麼事情是什麼嗎?


我也注意到,ResourcesTypedValue.TYPE_FLOATTypedValue.TYPE_DIMENSION。但在XML中,我不能寫type="float"

在評論中描述的解決方法是使用type=string,然後使用Float.parse獲取浮點數。這是必要的嗎?爲什麼或者爲什麼不?

回答

13

我知道這是一個遲到的答案,但你應該使用TypedValue#getFloat()而不是解析字符串到浮喜歡你的建議。

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

+1

這應該是公認的答案 – Peter 2014-12-31 16:32:39

+0

所以哪來這XML應該去? res/raw中的dimen xml? – 2016-03-06 11:07:20

+0

@G_V是的,我認爲是這樣 - 雖然我不認爲它真的很重要,因爲它全部都被'R'拾起呢? – Rich 2016-03-06 15:44:00

相關問題