2010-10-23 94 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)); 
    } 

}