2011-10-07 85 views
5

我正在開發android應用程序。我需要強調一些Textview。更改android中的下劃線的顏色

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

我已經使用了上述代碼。但是現在我想改變下劃線的顏色。任何人都可以告訴我該怎麼做。任何幫助或建議都被接受。

回答

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),所以我不能確定如何使用這些雖然。

+0

它不會工作,你有任何更多的建議。 –

+0

我想不出別的什麼。爲什麼它不工作?你試過了嗎? –

+0

是的,我有。但它不會改變下劃線的顏色。 –

5

沒有記錄方法來設置下劃線顏色。然而,存在一個未記錄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); 
     } 
    } 
} 
+0

我試過這個,調用工作,但下劃線的顏色仍然是黑色。 :( –

+2

對我來說是完美的工作,作爲對其他人的說明,1.0f是線寬倍數,1.0表示默認厚度,2.0表示厚度的兩倍 –

+0

它可以工作,但顏色和厚度不會從可以分類的( –

1

在TextPaint,必須有一個字段「underlineColor」和方法「setUnderlineText」,指示的和可以使用改變了下劃線顏色。但是,它們是'@hide'字段和方法,要使用它們,您必須使用如下反射:

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

ds是您的TextPaint對象。

相關問題