如何在TextView文本下划线并更改下划线的颜色

时间:2013-10-08 10:25:12

标签: android android-layout

我想为文本视图文本加下划线并将下划线的颜色更改为蓝色。我已经这样做但我的代码正在改变文本视图的颜色以及下划线。我想更改颜色只有下划线。我们怎么做呢。

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 个答案:

答案 0 :(得分:2)

你可以直接从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);
    }
}

现在只需在你的xml中正常使用它。我希望您知道如果要在xml中使用<path_to_LinedEditText.LinedEditText>标记而不是<EditText>,则会使用{{1}}标记。

答案 1 :(得分:2)

这应该可以帮到你

paint.setARGB(125,125,125,125);
paint.setflag(Paint.UNDERLINE_TEXT_FLAG);
textView.setPaintFlags( paint.getFlags());
textView.setText("UnderLined Text");

答案 2 :(得分:0)

为此你必须创建自定义控件:

这样适用于edittext