2010-10-23 43 views
21

在我的首選項屏幕上,我有一個首選項,單擊時打開一個顏色選擇器對話框。我想要做的是當用戶選擇一種顏色時,首選項的文本摘要以該顏色顯示。如何設置android偏好摘要文本顏色?

我知道我可以像這樣設置總結,Currently <font color="#ff0000">this color</font>並以該顏色顯示。問題是我回來的顏色是android int顏色。我可以使用紅色(),綠色(),藍色()方法,然後將它們轉換爲十六進制,然後將它們組合成一個字符串,以便我可以使用新值設置摘要文本,並且工作:String colorString = String.format("#%02x%02x%02x",Color.red(defaultColor), Color.green(defaultColor), Color.blue(defaultColor)); I只是好奇,如果有一個更簡單的方法來做到這一點。

提前致謝。

肖恩

回答

31

OK我結束了在使用Spannable做。這將顏色作爲整數。

Spannable summary = new SpannableString("Currently This Color"); 
summary.setSpan(new ForegroundColorSpan(color), 0, summary.length(), 0); 
preference.setSummary(summary); 
+0

非常感謝!這個工作完美無缺 – berlindev 2011-03-08 13:35:54

-1

嗨,你可以改變偏好使用Html.fromHtml()的顏色。

ex:private String title =「」+「設置短信發送限制」+「」;

並從你的Android應用程序添加這樣的字符串就像這樣。

CheckBoxPreference _test =(CheckBoxPreference)findPreference(「text」); _test .setTitle(Html.fromHtml(title));

請點擊此鏈接爲Android的HTML視圖: http://www.androidpeople.com/tag/html-tags/

感謝

+2

我意識到這一點。不過,就像我上面所說的那樣,我可以使用Android的顏色作爲int來存儲它。不是RGB或ARGB字符串。 – Sean 2010-10-28 20:42:36

2

有點晚了,但我發現寫這些自成體系的方法有用:

private void setColorPreferencesTitle(EditTextPreference textPref, int color) { 
    CharSequence cs  = (CharSequence) textPref.getTitle(); 
    String plainTitle = cs.subSequence(0, cs.length()).toString(); 
    Spannable coloredTitle = new SpannableString (plainTitle); 
    coloredTitle.setSpan(new ForegroundColorSpan(color), 0, coloredTitle.length(), 0); 
    textPref.setTitle(coloredTitle); 
} 

private void resetColorPreferencesTitle(EditTextPreference textPref) { 
    CharSequence cs  = (CharSequence) textPref.getTitle(); 
    String plainTitle = cs.subSequence(0, cs.length()).toString(); 
    textPref.setTitle(plainTitle); 
} 
3

使用Html.fromHtml風格你的文字。

mPodFolderPref.setTitle(Html.fromHtml("<font color='red'>" + mPodFolderPref.getTitle() + "</font>")); 
mPodFolderPref.setSummary(Html.fromHtml("<font color='red'>" + mPodFolderPref.getSummary() + "</font>")); 

Html.fromHtml可以爲您做很多事情。

+0

不知道爲什麼它被低估,但這是對問題最簡單的答案,也是最容易實現的。 – Mendhak 2014-10-11 14:16:39

+0

.fromHtml-solution還允許您更改大量屬性而不僅僅是文本顏色,例如以粗體顯示文本。因此,這對我來說是更有價值的答案。 Upvoted。 – MojioMS 2016-07-08 19:06:18

+0

其折舊。 – Yetti99 2017-03-23 18:56:05

1

以上所有方法都無濟於事。我結束了擴展Prefernces類:

public class CustomListPreferences extends Preference { 

    public CustomListPreferences(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public CustomListPreferences(Context context) { 
     super(context); 
    } 

    @Override 
    protected void onBindView(View view) { 
     super.onBindView(view); 
     ((TextView)view.findViewById(android.R.id.summary)).setTextColor(getContext().get Resources().getColor(R.color.green)); 
    } 

}