3

I want to underline a text view text and change the color of the underline as blue.I have done that but my code is changing the color of the text view as well as the underline.I want to change the color of the underline only.How can we do this.

TextView tv = (TextView) findViewById(R.id.tv);
        SpannableString content = new SpannableString(tv.getText().toString());
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        content.setSpan(new ForegroundColorSpan(Color.BLUE), 0, content.length(), 0);
        tv.setText(content);

3 Answers3

2

There you go, straight from https://android.googlesource.com/platform/development/+/froyo%5E/samples/NotePad/src/com/example/android/notepad/NoteEditor.java:

 public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;

    // we need this constructor for LayoutInflater
    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(0x800000FF);// line color
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int count = getLineCount();
        Rect r = mRect;
        Paint paint = mPaint;

        for (int i = 0; i < count; i++) {
            int baseline = getLineBounds(i, r);

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        }

        super.onDraw(canvas);
    }
}

Now just use it in your xml as normal. I hope that you know that you will use <path_to_LinedEditText.LinedEditText> tag instead of <EditText> if you want to use it inside xml.

M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103
2

This should help you

paint.setARGB(125,125,125,125);
paint.setflag(Paint.UNDERLINE_TEXT_FLAG);
textView.setPaintFlags( paint.getFlags());
textView.setText("UnderLined Text");
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
0

for this you will have to create custom control:

like this for edittext

Community
  • 1
  • 1
Hamad
  • 5,096
  • 13
  • 37
  • 65