【问题标题】:How to under line a TextView text and change the color of the underline如何在 TextView 文本下划线并更改下划线的颜色
【发布时间】:2013-10-08 10:25:11
【问题描述】:

我想为文本视图文本添加下划线并将下划线的颜色更改为蓝色。我已经这样做了,但是我的代码正在更改文本视图的颜色以及下划线。我想更改下划线的颜色仅下划线。我们如何才能做到这一点。

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);

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    这应该对你有帮助

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

    【讨论】:

    • setflag() 不是 Paint 的可解析方法。它是 setFlags()。
    • 这不会改变下划线的颜色,因为绘制对象只是将标志复制到 textView。
    【解决方案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 中使用它,你将使用&lt;path_to_LinedEditText.LinedEditText&gt; 标签而不是&lt;EditText&gt;

    【讨论】:

      【解决方案3】:

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

      edittext点赞

      【讨论】:

        猜你喜欢
        • 2015-04-08
        • 1970-01-01
        • 2012-09-15
        • 2016-10-22
        • 2021-03-10
        • 2018-09-11
        • 2017-07-23
        • 1970-01-01
        相关资源
        最近更新 更多