【问题标题】:Android: Statically underline dynamic text in TextViewAndroid:在TextView中静态下划线动态文本
【发布时间】:2011-06-08 03:01:39
【问题描述】:

我想让 TextView 完全加下划线,但我不能使用文本资源和 <u> 标签,因为它是动态文本。

相关:Can I underline text in an android layout?

到目前为止,我知道这样做的唯一方法是在运行时。这真的是唯一的方法吗?有没有办法在 XML 文件中做到这一点?

【问题讨论】:

    标签: android underline


    【解决方案1】:

    如果您愿意,也可以通过 /res/values/string.xml 文件执行此操作:例如,在 /res/values/string.xml 中,您可以添加如下条目:

    <string name="createAccount"><u>Create Account</u></string>
    

    然后在您的活动的 onCreate(Bundle savedInstanceState) 方法中,您将添加以下代码以使“创建帐户”> 在您为 xml 文件中定义的 createAccountText TextView 设置的 UI 中显示为下划线在/res/layout/ 中为您的活动:

    TextView createAccountText = (TextView) findViewById(R.id.createAccountText);
    Resources res = getResources();
    CharSequence styledText = res.getText(R.string.createAccount);
    createAccountText.setText(styledText, TextView.BufferType.SPANNABLE);
    

    【讨论】:

    • getResources().getText() 解决了我的问题,不知道为什么 textView.setText(getResources().getString(R.string.string_id)); 文本没有下划线。
    【解决方案2】:
     SpannableString content = new SpannableString(name);
     content.setSpan(new UnderlineSpan(), 0, name.length(), 0);
     geometrical_textview.setText(content, TextView.BufferType.SPANNABLE);
    

    【讨论】:

      【解决方案3】:

      peter3 之前写过扩展 TextView 类并重写 setText 方法。

      此解决方案不起作用,因为 setText 方法被标记为 FINAL。

      http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)

      不确定代码是否可以进行一些修改。

      【讨论】:

      • peter3 在他的回答中覆盖的方法不是 public final void setText(CharSequence 文本)而是 public void setText(CharSequence 文本,TextView.BufferType 类型)。 peter3 描述的方法不是最终的。 (添加评论有点晚了,但我也不得不看两次,所以认为值得一提)。
      【解决方案4】:

      最简单的解决方案可能是创建一个从 TextView 派生的自定义 UnderLineTextView 组件,覆盖 setText() 并将整个文本设置为下划线,如下所示(您上面提到的链接中的下划线代码):

      @Override
      public void setText(CharSequence text, BufferType type) {
          // code to check text for null omitted
          SpannableString content = new SpannableString(text);
          content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
          super.setText(content, BufferType.SPANNABLE);
      
      }
      

      然后只需在布局中使用新组件并照常设置文本即可。其余的会自动处理。

      有关自定义组件的更多信息: http://developer.android.com/guide/topics/ui/custom-components.html

      【讨论】:

        【解决方案5】:

        你可以在Html.fromHtml(String source)上加下划线

        例子:

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

        【讨论】:

        猜你喜欢
        • 2012-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 2011-07-06
        • 1970-01-01
        • 2015-01-25
        • 1970-01-01
        相关资源
        最近更新 更多