2014-02-08 48 views
1

我有colors.xml中定義的顏色資源。我想以編程方式設置此資源的值。我在我的應用程序中有一個設置選項,我將顯示一個調色板來選擇顏色,並且我想在顏色資源中設置所選的顏色。如何以編程方式在R.color中設置顏色

有什麼建議嗎?

+0

讀它你**不能**編輯資源編程。 –

回答

2

您無法以編程方式更改資源值,如colors.xml值。取而代之的是,你可以在SharedPreferences

+0

如果我有其他樣式依賴於顏色資源,該怎麼辦?那些如何以編程方式改變? – lokoko

+0

資源是一種只讀 –

2

保存您的「設置」您不能編輯XML文件那樣,而應該使用本地存儲,

保存在sharedpreferences你的顏色,當他們選擇它

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putInt("color", your_color_id); 
editor.commit(); 

然後,當你開始你的活動或片段等

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
int highScore = sharedPref.getInt("color", default_value); 
+0

editor.putInt(「color」,your_color_id); //會添加新的顏色嗎? sharedPref.getInt(「color」,R.id.white); //這會返回什麼? – lokoko

+0

它不會添加到你的XML,如果你問,它會存儲在本地的價值。您可以使用其他類型的顏色值。 –

+0

什麼是sharedPref.getInt(「color」,R.id.white);做什麼?爲什麼R.id.white? – lokoko

相關問題