更改android中下划线的颜色

时间:2011-10-07 08:04:53

标签: android underline

我正在开发android应用程序。我需要强调一些Textview。

SpannableString content = new SpannableString("Ack:");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
tvAck.setText(content);` 

我已经使用了上面的代码。但现在我想改变下划线的颜色。任何人都可以告诉我该怎么做。任何帮助或建议都被接受。

4 个答案:

答案 0 :(得分:7)

没有记录方法来设置下划线颜色。但是,有一种无证的TextPaint.setUnderline(int, float)方法,允许您提供下划线颜色和厚度:

final class ColoredUnderlineSpan extends CharacterStyle 
                                 implements UpdateAppearance {
    private final int mColor;

    public ColoredUnderlineSpan(final int color) {
        mColor = color;
    }

    @Override
    public void updateDrawState(final TextPaint tp) {
        try {
            final Method method = TextPaint.class.getMethod("setUnderlineText",
                                                            Integer.TYPE,
                                                            Float.TYPE);
            method.invoke(tp, mColor, 1.0f);
        } catch (final Exception e) {
            tp.setUnderlineText(true);
        }
    }
}

答案 1 :(得分:3)

我自己没有尝试过,所以这不是一个想法而是一个解决方案,但可能值得尝试。类UnderlineSpan包含方法updateDrawState,它将TextPaint作为参数。反过来,TextPain可以包含字段public int linkColor

所以对你来说就像是

TextPaint tp = new TextPaint();
tp.linkColor = [your color];           //not quite sure what the format should be
UnderlineSpan us = new UnderlineSpan();
us.updateDrawState(tp);
SpannableString content = new SpannableString("Ack:");
content.setSpan(us, 0, content.length(), 0); tvAck.setText(content);

TextPaintUnderlineSpan的参考都非常差,大部分javadoc完全丢失(自己判断:http://developer.android.com/reference/android/text/TextPaint.html),所以我不确定如何使用这些

答案 2 :(得分:1)

在TextPaint中,有一个字段'underlineColor'和方法'setUnderlineText',用于指示并可用于更改下划线颜色。但是,它们是'@hide'字段和方法,要使用它们,你必须使用反射,就像这样:

Field field = TextPaint.class.getDeclaredField("underlineColor");
field.setAccessible(true);
field.set(ds, mUnderlineColor);

ds是你的TextPaint对象。

答案 3 :(得分:0)

遇到这个场景真的很晚。这是另一种方法,那就是将多个跨度设置为相同的可跨度内容:

SpannableString content = new SpannableString("Ack:");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
content.setSpan(
        new ForegroundColorSpan(ContextCompat.getColor(context, R.color.red)),
        0,
        content.length(),
        0
);
tvAck.setText(content, TextView.BufferType.SPANNABLE);
相关问题