【问题标题】:Can underline words in TextView text可以在 TextView 文本中为单词加下划线
【发布时间】:2012-01-23 09:35:20
【问题描述】:

在 android 中是否有可能在 Java 代码中为 TextView 提供一些带有 setText(text) 函数的文本,这些文本带有基本标签,如和 以使标记的单词加下划线?

【问题讨论】:

标签: android android-widget


【解决方案1】:

是的,你可以,使用 Html.fromhtml() 方法:

textView.setText(Html.fromHtml("this is <u>underlined</u> text"));

【讨论】:

  • 好吧,我遇到了一个问题。这是不起作用的代码行。 textView.setText(Html.fromHtml(getResources().getString(R.string.have_activation_code)));&lt;string name="have_activation_code"&gt;&lt;u&gt;I have activation code&lt;/u&gt;&lt;/string&gt;
  • @mahbub.kuet 您必须将 HTML 字符串放入 。所以 我有激活码]]>
  • Html.fromHtml 现已弃用
【解决方案2】:

定义一个字符串为:

<resources>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

【讨论】:

【解决方案3】:

您可以使用 SpannableString 类中的 UnderlineSpan:

SpannableString content = new SpannableString(<your text>);
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);

那就用textView.setText(content);

【讨论】:

    【解决方案4】:
    tobeunderlined= <u>some text here which is to be underlined</u> 
    
    textView.setText(Html.fromHtml("some string"+tobeunderlined+"somestring"));
    

    【讨论】:

      【解决方案5】:

      最简单的方法

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

      还支持 TextView 子类,例如 EditText、Button、Checkbox

      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 的多个部分下划线?

      然后Check This Answer

      【讨论】:

        猜你喜欢
        • 2017-01-31
        • 2012-10-10
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-08
        • 2012-09-07
        • 2013-04-29
        相关资源
        最近更新 更多