1

我正在尝试以编程方式将 ForegroundColorSpan 设置到操作栏 MenuItem ...

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater mInflater = getSupportMenuInflater();
    mInflater.inflate(R.menu.menu_main, menu);

    MenuItem menuProfile = menu.findItem(R.id.profile);
    menuProfile.setTitle(createProfileMenuTitle(this));
}

public static SpannableStringBuilder createProfileMenuTitle(Context c)
{
    SpannableStringBuilder b = new SpannableStringBuilder();

    int s = b.length();
    b.append(c.getString(R.string.Username));
    int e = b.length();
    b.setSpan(new ForegroundColorSpan(c.getResources().getColor(R.color.someColor)), s, e, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    b.append(" ..some more text here");

    return b;
}

它不工作。知道如何解决这个问题吗?(没有在 MenuItem 上使用 setActionView 这样做会失去默认布局样式的所有所需行为)

4

2 回答 2

1

有一个答案:

在您的主题中,默认 actionMenuTextAppearance 是TextAppearance.Holo.Widget.ActionBar.Menu

<item name="actionMenuTextAppearance">@android:style/TextAppearance.Holo.Widget.ActionBar.Menu</item>

而 setSpan(ForegroundColorSpan) 在此 TextAppearance 中不起作用。

你可以简单地设置

 <item name="android:actionMenuTextAppearance">@android:style/TextAppearance.Holo.Widget.ActionMode.Title</item>

像这样:

 <style name="YourTheme" parent="android:Theme.Holo.Light">
        <item name="android:actionMenuTextAppearance">@android:style/TextAppearance.Holo.Widget.ActionMode.Title</item>
 </style>

那么它的工作原理!

于 2015-01-13T10:07:22.610 回答
-1

尝试:

markup = "your text in html with colors";
Spanned spannable = Html.fromHtml(markup);
于 2013-02-10T01:32:09.443 回答