如何使用与文本不同的颜色为TextView中的文本加下划线?

Vip*_*l J 13 android textview android-layout

我知道如何在textview中为文本加下划线.但是如何用不同颜色强调文字?下划线可以通过以下方式完成:

TextView t = (TextView) findViewById(R.id.textview);
t.setPaintFlags(t.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
t.setText("Underline Text");
Run Code Online (Sandbox Code Playgroud)

假设我的textcolor是黑色的,我想用蓝色加下划线,怎么做?提前致谢.

Boj*_*man 17

我遇到了同样的问题,在阅读其他帖子时,我偶然发现了Layout类EditText.它通过手动绘制带有画布的下划线,提供了实现此目的所需的一切.

首先,我定义了自定义属性,以便在XML布局文件中轻松自定义

<declare-styleable name="UnderlinedTextView" >
    <attr name="underlineWidth" format="dimension" />
    <attr name="underlineColor" format="color" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

和一个自定义TextView类

public class UnderlinedTextView extends AppCompatTextView {

    private Rect mRect;
    private Paint mPaint;
    private float mStrokeWidth;

    public UnderlinedTextView(Context context) {
        this(context, null, 0);
    }

    public UnderlinedTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public UnderlinedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attributeSet, int defStyle) {

        float density = context.getResources().getDisplayMetrics().density;

        TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.UnderlinedTextView, defStyle, 0);
        int underlineColor = typedArray.getColor(R.styleable.UnderlinedTextView_underlineColor, 0xFFFF0000);
        mStrokeWidth = typedArray.getDimension(R.styleable.UnderlinedTextView_underlineWidth, density * 2);
        typedArray.recycle();

        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(underlineColor);
        mPaint.setStrokeWidth(mStrokeWidth);
    }

    public int getUnderLineColor() {
        return mPaint.getColor();
    }

    public void setUnderLineColor(int mColor) {
        mPaint.setColor(mColor);
        invalidate();
    }

    public float getUnderlineWidth() {
        return mStrokeWidth;
    }

    public void setUnderlineWidth(float mStrokeWidth) {
        this.mStrokeWidth = mStrokeWidth;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        int count = getLineCount();

        final Layout layout = getLayout();
        float x_start, x_stop, x_diff;
        int firstCharInLine, lastCharInLine;

        for (int i = 0; i < count; i++) {
            int baseline = getLineBounds(i, mRect);
            firstCharInLine = layout.getLineStart(i);
            lastCharInLine = layout.getLineEnd(i);

            x_start = layout.getPrimaryHorizontal(firstCharInLine);
            x_diff = layout.getPrimaryHorizontal(firstCharInLine + 1) - x_start;
            x_stop = layout.getPrimaryHorizontal(lastCharInLine - 1) + x_diff;

            canvas.drawLine(x_start, baseline + mStrokeWidth, x_stop, baseline + mStrokeWidth, mPaint);
        }

        super.onDraw(canvas);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后它的用法很简单

<some.package.UnderlinedTextView
    android:id="@+id/tvTest"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:gravity="center"
    android:text="This is a demo text"
    android:textSize="16sp"
    app:underlineColor="#ffc112ef"
    app:underlineWidth="3dp"/>
Run Code Online (Sandbox Code Playgroud)

最后结果

  • 多线

    在此输入图像描述
  • 单线

    在此输入图像描述


GrI*_*sHu 5

您可以尝试如下:

  String styledText = "<u><font color='red'>Underline Text</font></u>.";
  textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Run Code Online (Sandbox Code Playgroud)

  • 这也会改变文本的颜色,我只想设置下划线的颜色。谢谢 (2认同)

and*_*per 5

另一个解决方案,这次不扩展 TextView(基于我很久以前写的一个问题,这里):

有一个 drawable 显示为下划线,并有一个文本本身的跨度:

text_underline.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <padding android:bottom="10dp"/>
    <stroke
        android:width="1dp"
        android:color="#3792e5"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

DrawableSpan.kt

class DrawableSpan(private val drawable: Drawable) : ReplacementSpan() {
    private val padding: Rect = Rect()

    init {
        drawable.getPadding(padding)
    }

    override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
        val rect = RectF(x, top.toFloat(), x + measureText(paint, text, start, end), bottom.toFloat())
        drawable.setBounds(rect.left.toInt() - padding.left, rect.top.toInt() - padding.top, rect.right.toInt() + padding.right, rect.bottom.toInt() + padding.bottom)
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
        drawable.draw(canvas)
    }

    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int = Math.round(paint.measureText(text, start, end))

    private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float = paint.measureText(text, start, end)

}
Run Code Online (Sandbox Code Playgroud)

用法:

    val text = getString(R.string.large_text)
    val spannable = SpannableString(text)
    spannable.setSpan(DrawableSpan(resources.getDrawable(R.drawable.text_underline)), 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.setText(spannable, TextView.BufferType.SPANNABLE)
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明


Ahm*_*kri -1

    Paint p = new Paint();
    p.setColor(Color.RED);

    TextView t = (TextView) findViewById(R.id.textview);
    t.setPaintFlags(p.getColor());
    t.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    t.setText("Underline Text");    
Run Code Online (Sandbox Code Playgroud)

制作新的油漆颜色。并将绘画分配给文本视图。