android - ForegroundColorSpan 不适用于 ReplacementSpan

标签 android spannablestring

我正在尝试利用 ReplacementSpans 来格式化 EditText 字段中的输入(不修改内容):

public class SpacerSpan extends ReplacementSpan {
    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        return (int) paint.measureText(text.subSequence(start,end)+" ");
    }
    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        canvas.drawText(text.subSequence(start,end)+" ", 0, 2, x, y, paint);
    }
}

这按预期工作,并在跨接部分后添加了间距。 但是,如果我还应用 ForegroundColorSpan,则不会为跨区设置颜色:

EditText edit = (EditText) findViewById(R.id.edit_text);

SpannableString content = new SpannableString("1234567890");

ForegroundColorSpan fontColor = new ForegroundColorSpan(Color.GREEN);
SpacerSpan spacer = new SpacerSpan();
content.setSpan(fontColor, 0, content.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
content.setSpan(spacer, 4, 5, Spanned.SPAN_MARK_MARK);

edit.setText(content);

结果看起来像 http://i.cubeupload.com/4Us5Zj.png

如果我应用 AbsoluteSizeSpan,指定的字体大小也会应用到 Replacement Span 部分。这是预期的行为,是我遗漏了什么,还是 android 中的错误?

最佳答案

CommonWare 为我指明了正确的方向。 似乎 ReplacementSpans 在查询任何 CharacterStyleSpan 之前呈现 [1]

一个可能的(但丑陋的)修复是实现一个扩展 MetricAffectingSpan 的自定义 ForegroundColorSpan(在绘制 ReplacementSpans [1] 之前咨询 MetricAffectingSpans)。

public class FontColorSpan extends MetricAffectingSpan {

    private int mColor;

    public FontColorSpan(int color) {
        mColor = color;
    }

    @Override
    public void updateMeasureState(TextPaint textPaint) {
        textPaint.setColor(mColor);
    }
    @Override
    public void updateDrawState(TextPaint textPaint) {
        textPaint.setColor(mColor);
    }
} 

我想这是一个应该报告的错误?

[1] http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/text/TextLine.java#936

关于android - ForegroundColorSpan 不适用于 ReplacementSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28323901/

相关文章:

android - 在 SpannableString 中获取应用跨度的范围

Android:更改 Spannable String 中换行符的高度不起作用

android - 多个段落上的 LeadingMarginSpan

android - OpenGLRenderer : Path Too Large To Be Rendered To a Texture 问题

android - Kotlin 静态函数 : companion object, @JvmStatic @JvmField

java - 添加到数组列表在 For 循环中不起作用

java - com.android.phone 停止工作

android - 如何使 TextView 中特定单词的出现可点击

android - AppCompat v7 :21 Split Action Bar Broken?

android - 单击 ClickableSpan 后如何禁用打开键盘