Android:具有多种颜色和字体的TextView

好的,所以我认为这应该是一个相当简单的过程.

我已阅读以下问题:

> Multiple Typefaces in the same TextView
> Multiple Typefaces in the same TextView
> Put in bold some parts of a TextView
> Making part of a string bold in TextView

在所有这些问题和答案中,建议似乎都非常相似.我试图避免使用HTML技术,而是改用SpannableString和SpannableStringBuilder.最终,我希望能够在单个TextView中使用多个不同的字体,但是现在,我只想弄清楚如何使多种颜色起作用.

我正在尝试以这种方式实现这些技术:

// Get a typeface for my custom font
String regularFontPath          = "fonts/Abel-Regular.ttf";
Typeface regularTf              = Typeface.createFromAsset(getActivity().getAssets(), regularFontPath);

// Set the label's typeface (this part is working)
mItemCodesLabel.setTypeface(regularTf);

// Create a spannable builder to build up my
// TextView's content from data
SpannableStringBuilder builder  = new SpannableStringBuilder();

// These colors are defined and working well in other parts of my app
ForegroundColorSpan ltGraySpan  = new ForegroundColorSpan(R.color.light_gray);
ForegroundColorSpan dkGraySpan  = new ForegroundColorSpan(R.color.dark_gray);

// mCodesList has good data and the actual data output from this
// loop is correct. Just the styling is wrong
for (int i = 0; i < mCodesList.size(); i = i + 1) {
    ParseObject code            = mCodesList.get(i);
    String value                = code.getString("value") + " | ";
    if (i > 0) {
        // I want new codes to be on a new line (this works)
        value                   = "\n" + value;
    }
    SpannableString valueSpan   = new SpannableString(value);
    valueSpan.setSpan(ltGraySpan, 0, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(valueSpan);

    String loc                  = code.getString("location");
    SpannableString locSpan     = new SpannableString(loc);
    locSpan.setSpan(dkGraySpan, 0, loc.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(locSpan);
}
mItemCodesLabel.setText(builder);

最终结果是TextView包含正确的文本内容. TextView是正确的字体.但是TextView的全部内容都是我的@ color / light_gray颜色.我不确定为什么,因为在XML布局文件中,我指定了@ color / dark_gray颜色(希望通过设置Spannable设置文本来覆盖该颜色).即使我将两个ForegroundColorSpan对象都更改为使用R.color.dark_gray,TextView仍然显示为浅灰色.我没有在代码的其他任何地方设置文本的颜色,所以我真的很茫然.

我在运行4.4.2的LG Optimus G Pro上运行它.我还有另一个TextView,我需要在其中获得多种颜色和字体,甚至在文本的某些部分下划线,所以对我来说这是一个很大的问题.我要去哪里错了?

解决方法:

使用getResource().getColor(R.color.light_gray)检索要传递给ForegroundColorSpan的颜色.我怀疑它是在内部为您检索.您可能需要在每次迭代时实例化一个新的ForegroundColorSpan.无法重复使用

上一篇:Python 字典键映射多个值,字典值为列表,defaultdict


下一篇:python 设置默认字典