我能否在Android布局中下划线文本?

809

我如何在 Android 布局 xml 文件中定义 下划线 文本?


这里我用示例描述了最佳实践。请查看此回答链接:[https://dev59.com/1Gsz5IYBdhLWcg3wOlSh#67087554]。 - Mayur Dabhi
29个回答

15
如果您想在XML中实现此功能,请在资源文件中声明字符串,并将该资源值放入HTML的下划线标签(<u></u>)中。然后在TextView中添加该字符串。
android:text="@string/your_text_reference"

在字符串资源值中,

<string name="your_text_reference"><u>Underline me</u></string>

如果您想通过编程实现此操作,对于Kotlin,可以使用

textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG

或者,

textView.text = Html.fromHtml("<p><u>Underline me</u></p>")

11
我知道这是一个晚回答,但我想出了一个相当不错的解决方案... 我采用了Anthony Forloney关于在代码中下划线文本的答案,并创建了一个TextView的子类,它可以为您处理这个问题。然后,每当您想要一个带有下划线的TextView时,您只需在XML中使用这个子类即可。
以下是我创建的类:
import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created with IntelliJ IDEA.
 * User: Justin
 * Date: 9/11/13
 * Time: 1:10 AM
 */
public class UnderlineTextView extends TextView
{
    private boolean m_modifyingText = false;

    public UnderlineTextView(Context context)
    {
        super(context);
        init();
    }

    public UnderlineTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    public UnderlineTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

    private void init()
    {
        addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
                //Do nothing here... we don't care
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //Do nothing here... we don't care
            }

            @Override
            public void afterTextChanged(Editable s)
            {
                if (m_modifyingText)
                    return;

                underlineText();
            }
        });

        underlineText();
    }

    private void underlineText()
    {
        if (m_modifyingText)
            return;

        m_modifyingText = true;

        SpannableString content = new SpannableString(getText());
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        setText(content);

        m_modifyingText = false;
    }
}

现在,如果您想在XML中创建一个带有下划线的文本视图,只需要按照以下步骤进行:
<com.your.package.name.UnderlineTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:gravity="center"
    android:text="This text is underlined"
    android:textColor="@color/blue_light"
    android:textSize="12sp"
    android:textStyle="italic"/>

我在这个XML片段中添加了其他选项,以显示我的示例可以改变文本的颜色、大小和样式...

希望这可以帮到你!


2
虽然这个例子可以工作,但我很快意识到如果你想在XML中拥有额外的控制权,这种方法就不够用了... 我已经转向了一个更好的解决方案,它包括以下步骤:1)子类化textview 2)通过自定义属性添加支持来实现上述下划线。唯一的区别是,只有在设置了自定义属性时才执行下划线代码。 - Justin

11

最新的绘制下划线文本方法由Romain Guy在medium上介绍,并提供了在GitHub上的源代码。

  • 一个基于Path的实现需要API level 19
  • 一个基于Region的实现需要API level 1

enter image description here


9

最简单的方法

TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");

也支持像EditText、Button和Checkbox这样的TextView子类。
public void setUnderLineText(TextView tv, String textToUnderLine) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToUnderLine, 0);

        UnderlineSpan underlineSpan = new UnderlineSpan();
        SpannableString wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToUnderLine, ofs);
            if (ofe == -1)
                break;
            else {
                wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

如果您想要:
- 点击时有下划线的文本? - 下划线多个 TextView 的部分?
那么请查看 此答案

8

在字符串资源文件中使用 translatable 属性,例如:

<string name="example"><u>Example</u></string>

8
我使用了这个XML drawable来创建一个底部边框,并将该drawable应用为我的TextView的背景。
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item android:top="-5dp" android:right="-5dp" android:left="-5dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                    android:width="1.5dp"
                    android:color="@color/pure_white" />
        </shape>
    </item>
</layer-list>

这是所有视图使用自定义颜色下划线的完美解决方案。请勿忽略透明背景,因为在 Android 4 中需要它,否则您的视图将没有黑色背景。 - Ivan Mitsura

8

一个简单灵活的xml解决方案:

<View
  android:layout_width="match_parent"
  android:layout_height="3sp"
  android:layout_alignLeft="@+id/your_text_view_need_underline"
  android:layout_alignRight="@+id/your_text_view_need_underline"
  android:layout_below="@+id/your_text_view_need_underline"
  android:background="@color/your_color" />

如果文本跨越多行,则此方法将无法正常工作。 - Mike Walker

7

使用Class尝试

对于Java语言

textview.setPaintFlags(textview.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);

对于 Kotlin

textview.setPaintFlags(textview.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)

7
另一种解决方案是创建一个定制视图,扩展TextView,如下所示。
public class UnderLineTextView extends TextView {

    public UnderLineTextView(Context context) {
        super(context);
        this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    public UnderLineTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

}

只需按照下面所示的方式将其添加到xml中即可。
<yourpackage.UnderLineTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="underline text"
 />

太棒了!但是下划线的颜色是灰色的,如何将其更改为黑色或其他颜色? - OhhhThatVarun

5
非常简洁的 Kotlin 版本:
tvTitle.apply { 
    text = "foobar"
    paint?.isUnderlineText = true
}

这个答案与4月5日发布的答案有何不同? - Edric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接