25

在我的偏好屏幕上,我有一个偏好,点击它会打开一个颜色选择器对话框。我想做的是当用户选择一种颜色时,偏好的文本摘要以该颜色显示。

我知道我可以像这样设置摘要,Currently <font color="#ff0000">this color</font>并以该颜色显示。问题是我回来的颜色是 android int 颜色。

我可以使用 red()、green()、blue() 方法,然后将它们转换为十六进制,然后将它们组合成一个字符串,这样我就可以使用新值设置摘要文本并且有效:String colorString = String.format("#%02x%02x%02x",Color.red( defaultColor ), Color.green( defaultColor ), Color.blue( defaultColor ));我只是好奇是否有是一种更简单的方法。

提前谢谢。

肖恩

4

5 回答 5

36

好的,我最终做的是使用 Spannable。这将颜色作为整数。

Spannable summary = new SpannableString("Currently This Color");
summary.setSpan(new ForegroundColorSpan(color), 0, summary.length(), 0);
preference.setSummary(summary);
于 2010-10-28T20:47:47.960 回答
5

使用 Html.fromHtml 设置文本样式。

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

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

于 2014-03-13T22:12:54.403 回答
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);
}
于 2012-03-14T15:20:03.000 回答
2

以上所有方法都没有帮助我。我最终扩展了 Preferences 类:

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));
    }

}
于 2015-10-15T08:46:49.190 回答
-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/

谢谢

于 2010-10-28T05:43:01.750 回答