Trying to change the underline color of a Spannable string

I'm trying to change the underline color of a spannable string so that the underline and the font have different colors. Apparently you can do this in java by using reflection and changing the underlinecolor property of the TextPaint object. Is there a way in Xamarin to use reflection on the underlying java object to make this same change.

http://stackoverflow.com/questions/7684560/change-the-color-of-the-underline-in-android

Here's the relevant (java) code snippet:

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

Answers

  • RobertGruenRobertGruen USMember

    So I got the proper reflection code and can modify both the underlineColor field and setUnderlineText method but no luck, underline color is not changing. I've created my own Span class by inheriting from CharacterStyle and then in the UpdateDrawstate do the following:

        public override void UpdateDrawState(TextPaint tp)
        {
            tp.Density = 2.0F;
            tp.Flags = Android.Graphics.PaintFlags.UnderlineText;
            tp.StrokeWidth = 1.5F;
            tp.BgColor = Android.Graphics.Color.ParseColor("#FF00FFFF");
            tp.LinkColor = Android.Graphics.Color.ParseColor("#FF00FF00");
            tp.UnderlineText = true;
    
            Java.Lang.Class textPaintJClass = tp.Class;
            Java.Lang.Reflect.Field underlineColorField = textPaintJClass.GetDeclaredField("underlineColor");
            underlineColorField.Accessible = true;
            underlineColorField.SetInt(tp, Android.Graphics.Color.ParseColor("#FF00FF00"));
    
            Java.Lang.Reflect.Method m = textPaintJClass.GetDeclaredMethod("setUnderlineText", new Java.Lang.Class[] { Java.Lang.Integer.Type, Java.Lang.Float.Type });
            Java.Lang.Integer i = new Java.Lang.Integer(Android.Graphics.Color.ParseColor("#FFFFFF00"));
            Java.Lang.Float f = new Java.Lang.Float(1.0F);
            m.Invoke(tp, new Java.Lang.Object[] { i, f });
        }
    
Sign In or Register to comment.