如何在运行时在android中使文本加粗?


97

一个ListView在我的应用程序有很多字符串元素,如nameexperiencedate of joining,等我只是想name大胆。所有的字符串元素都将在一个中TextView

我的XML:

<ImageView
    android:id="@+id/logo"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="15dp" >
</ImageView>

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/logo"
    android:padding="5dp"
    android:textSize="12dp" >
</TextView>

我的代码来设置ListView项的TextView:

holder.text.setText(name + "\n" + expirience + " " + dateOfJoininf);

Answers:


229

假设您有一个TextView电话etx。然后,您将使用以下代码:

final SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");

final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan iss = new StyleSpan(android.graphics.Typeface.ITALIC); //Span to make text italic
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold 
sb.setSpan(iss, 4, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic

etx.setText(sb);


2
对于Xamarin,请像这样使用var bss = new StyleSpan(Android.Graphics.TypefaceStyle.Bold);
Elisabeth

对于Xamarin,etx.TextFormatted = sb;
大流士(Darius)

27

根据Imran Rana的回答,如果您需要将StyleSpans应用于多个TextViews,并且支持多种语言(索引是可变的),则这是一种通用的可重用方法:

void setTextWithSpan(TextView textView, String text, String spanText, StyleSpan style) {
    SpannableStringBuilder sb = new SpannableStringBuilder(text);
    int start = text.indexOf(spanText);
    int end = start + spanText.length();
    sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(sb);
}

Activity像这样使用它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...

    StyleSpan boldStyle = new StyleSpan(Typeface.BOLD);
    setTextWithSpan((TextView) findViewById(R.id.welcome_text),
        getString(R.string.welcome_text),
        getString(R.string.welcome_text_bold),
        boldStyle);

    // ...
}

strings.xml

<string name="welcome_text">Welcome to CompanyName</string>
<string name="welcome_text_bold">CompanyName</string>

结果:

欢迎来到CompanyName


12

此处提供的答案是正确的,但不能循环调用,因为StyleSpan对象是单个连续范围(不是可以应用于多个范围的样式)。setSpan使用相同的粗体调用多次StyleSpan会创建一个粗体跨度,并在父跨度中四处移动。

就我而言(显示搜索结果),我需要使所有搜索关键字的所有实例都显示为粗体。这就是我所做的:

private static SpannableStringBuilder emboldenKeywords(final String text,
                                                       final String[] searchKeywords) {
    // searching in the lower case text to make sure we catch all cases
    final String loweredMasterText = text.toLowerCase(Locale.ENGLISH);
    final SpannableStringBuilder span = new SpannableStringBuilder(text);

    // for each keyword
    for (final String keyword : searchKeywords) {
        // lower the keyword to catch both lower and upper case chars
        final String loweredKeyword = keyword.toLowerCase(Locale.ENGLISH);

        // start at the beginning of the master text
        int offset = 0;
        int start;
        final int len = keyword.length(); // let's calculate this outside the 'while'

        while ((start = loweredMasterText.indexOf(loweredKeyword, offset)) >= 0) {
            // make it bold
            span.setSpan(new StyleSpan(Typeface.BOLD), start, start+len, SPAN_INCLUSIVE_INCLUSIVE);
            // move your offset pointer 
            offset = start + len;
        }
    }

    // put it in your TextView and smoke it!
    return span;
}

请记住,如果一个关键字是另一个关键字的子串,则上面的代码不够聪明,无法跳过双引号。例如,如果您在“菲斯海中的鱼”中搜索“ Fish fi” 它将使“ fish” 变粗一次,然后使“ fi”部分变粗。好处是,虽然效率低下并且有点不可取,但不会出现视觉缺陷,因为您的显示结果仍然看起来像

在ES 网络猪圈海




5

如果您不完全知道要加粗的文本部分之前的文本长度,或者甚至不知道要加粗的文本长度,则可以轻松地使用如下HTML标记:

yourTextView.setText(Html.fromHtml("text before " + "<font><b>" + "text to be Bold" + "</b></font>" + " text after"));

0

将弗里德的答案扩展到支持案例和变音符号的不敏感性。

public static String stripDiacritics(String s) {
        s = Normalizer.normalize(s, Normalizer.Form.NFD);
        s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
        return s;
}

public static void setTextWithSpan(TextView textView, String text, String spanText, StyleSpan style, boolean caseDiacriticsInsensitive) {
        SpannableStringBuilder sb = new SpannableStringBuilder(text);
        int start;
        if (caseDiacriticsInsensitive) {
            start = stripDiacritics(text).toLowerCase(Locale.US).indexOf(stripDiacritics(spanText).toLowerCase(Locale.US));
        } else {
            start = text.indexOf(spanText);
        }
        int end = start + spanText.length();
        if (start > -1)
            sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textView.setText(sb);
    }

0

如果使用@ srings / your_string批注,请访问strings.xml文件,并<b></b>在所需文本部分中使用标记。

例:

    <string><b>Bold Text</b><i>italic</i>Normal Text</string>

-1

我建议对CDATA使用strings.xml文件

<string name="mystring"><![CDATA[ <b>Hello</b> <i>World</i> ]]></string>

然后在java文件中:

TextView myTextView = (TextView) this.findViewById(R.id.myTextView);
myTextView.setText(Html.fromHtml( getResources().getString(R.string.mystring) ));
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.