2013-01-24 20 views
2

顏色。如果我有RES /價值/色彩與自定義顏色的XML文件是這樣的:調用從XML文件

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<drawable name="red">#ff0000</drawable> 
<drawable name="blue">#0000ff</drawable> 
<drawable name="green">#00ff00</drawable> 
</resources> 

如何使用在其他代碼從它的顏色或其它值?

如何將這些用於參數?類似於:

int green = context.getResources().getColor(R.color.green); 
    g.drawRect(1, 1, 181, 121, green); 

在logcat中給出錯誤並使程序崩潰。因此,如果colors.xml在res/values/ ,並且我已經導入了上下文,那麼我如何使用綠色,例如在參數中?

+1

爲什麼您不使用#ff0000而不是#ff0000。如果你能這樣做,那麼@anthropomo答案肯定會幫助你。 –

+0

非常好的一點,@Narendra!更新我的答案... – anthropomo

+0

drawRect中的最後一個參數是Paint類型,所以您必須創建一個類似於答案中的Paint,然後將其作爲最後一個參數提供。不久之前我就是新人了。在我學習的每種語言中,GUI都很困難。 – anthropomo

回答

2

首先,在您的xml中將drawable更改爲color

然後你需要有上下文。它是這樣的:

context.getResources().getColor(R.color.green);

它返回一個int顏色值。

編輯:

對於其他價值,在這裏看到的功能:

http://developer.android.com/reference/android/content/res/Resources.html

我喜歡TP讓我所有的XML顏色一次​​,並從那裏通過他們周圍,所以我不會打字以上一遍又一遍。不知道這是否被認爲是最佳做法。

如果你想在塗料使用此,則可能是:

// Declare this at the beginning: 
Paint green paint; 
// This goes in the constructor: 
greenPaint = new Paint(); 
greenPaint.setColor(context.getResources().getColor(R.color.green)); 
// then draw something in onDraw, for example: 
canvas.drawRect(5,5,5,5, greenPaint); 

如果你想使用它在多個塗料等,其保存爲一個int:

int greenNum = context.getResources().getColor(R.color.green); 
+0

很好,現在它完美無瑕。 –