【问题标题】:Way to set text style programmatically in Android widget?在Android小部件中以编程方式设置文本样式的方法?
【发布时间】:2010-11-08 16:01:29
【问题描述】:

我看到有一个TextAppearanceSpan 可用,但没有使用示例。我只想将文本加粗,并保持其他所有内容不变 - 是否有更简单的方法可以以编程方式执行此操作?

【问题讨论】:

  • 仅供参考,这是用于在 Tab 小部件上设置标题。

标签: android text coding-style widget


【解决方案1】:

您只需要在 res/values 中创建一个 xml 文件并编写如下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="header">
        /** here goes the style */
    </style>
</resources>

那么您只需将生成的 R.style.header 传递给 TextAppearanceSpan 构造函数。

【讨论】:

  • 我的标签是 TextViews,所以我最终使用 Spannable 类来应用样式。
【解决方案2】:

记录在 http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext ,看第二种方式使用Spannable

具体

// Get our EditText object.
EditText vw = (EditText)findViewById(R.id.text); // or new etc

// Set the EditText's text.
vw.setText("Italic, highlighted, bold.");

// Get the EditText's internal text storage
Spannable str = vw.getText();

// Create our span sections, and assign a format to each.
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-06
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2012-04-12
    相关资源
    最近更新 更多