Kotlin 使用 SpannableString 设置两种不同的文本样式以动态更改文本视图中的文本

Kotlin set two different text styles to dynamically changing text in a text view using SpannableString

我有一个文本视图,其值可以更改。例如,压力。它可以有不同的长度——即 999.1 或 1010.2 hPa。

文本看起来像这样:

我需要为文本的第一部分(数字 - 1024.12)和文本的第二部分(度量单位)设置不同的文本样式。

到目前为止我已经尝试过:

  1. 使用 SpannableString 并将 span 设置为相同的可扫描字符串。

  2. 创建两个可扫描字符串,分别在它们上设置跨度,连接两个可扫描字符串并设置连接可扫描字符串作为文本到文本视图:

//the value of measurement
val spannable1 = SpannableString(button.customView.tvBottom.text.split(" ")[0]) 
//the unit of measurement
val spannable2 = SpannableString(button.customView.tvBottom.text.split(" ")[1]) 
                
spannable1.setSpan(R.style. Bold20Dark, 0, spannable1.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
spannable2.setSpan(R.style. Regular12Dark, 0, spannable2.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                
val spannableString = spannable1.toString() + spannable2.toString()
button.customView.tvBottom.setText(spannableString)

让我受不了的是数字和它的长度是动态变化的,所以如果它不断变化,我不知道如何设置一个稳定的范围。

我所说的不同文本样式是指以下样式:

 <style name="Bold20Dark">
        <item name="android:textSize">20sp</item>
        <item name="android:lineSpacingExtra">3sp</item>
        <item name="android:textColor">@color/dark</item>
        <item name="android:fontFamily">@font/fonr_bold</item>
    </style>

    <style name="Regular12Dark">
        <item name="android:gravity">center_horizontal</item>
        <item name="android:textSize">12sp</item>
        <item name="android:lineSpacingExtra">4sp</item>
        <item name="android:fontFamily">@font/font_regular</item>
        <item name="android:textColor">@color/grey</item>
    </style>

如果范围可变,有没有办法设置两种文本样式?谢谢。

这可能对你有帮助..

TextView txtView = (TextView) findViewById(R.id.text);
        String number ="1024.12";
        String unit = " hPa";

        SpannableString spannableString = new SpannableString(number+unit);
        spannableString.setSpan( new BottomAlignSuperscriptSpan( (float)0.35 ), number.length(), number.length()+unit.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
        txtView.setText(spannableString);

BottomAlignSuperscriptSpan.java

import android.text.TextPaint;
import android.text.style.SuperscriptSpan;

public class BottomAlignSuperscriptSpan extends SuperscriptSpan {

    //divide superscript by this number
    protected int fontScale = 2;
    //shift value, 0 to 1.0
    protected float shiftPercentage = 0;
    //doesn't shift
    BottomAlignSuperscriptSpan() {}
    //sets the shift percentage
    BottomAlignSuperscriptSpan( float shiftPercentage ) {
        if( shiftPercentage > 0.0 && shiftPercentage < 1.0 )
            this.shiftPercentage = shiftPercentage;
    }
    @Override
    public void updateDrawState( TextPaint tp ) {
        //original ascent
        float ascent = tp.ascent();
        //scale down the font
        tp.setTextSize( tp.getTextSize() / fontScale );
        //get the new font ascent
        float newAscent = tp.getFontMetrics().ascent;
        //move baseline to top of old font, then move down size of new font
        //adjust for errors with shift percentage
//        tp.baselineShift += ( ascent - ascent * shiftPercentage )
//                - (newAscent - newAscent * shiftPercentage );
    }
    @Override
    public void updateMeasureState( TextPaint tp ) {
        updateDrawState( tp );
    }
}

您可以创建一个 spannable 工厂,覆盖 newSpannable 方法并将其设置为 TextView。您只需确保将 setText 称为 setText(string, BufferType.SPANNABLE)

val spannableFactory = object : Spannable.Factory() {
    override fun newSpannable(source: CharSequence?): Spannable {
        val spannable = source!!.toSpannable()
        val len1 = source.split(" ")[0].length
        val len2 = source.split(" ")[1].length

        spannable.setSpan(ForegroundColorSpan(Color.RED), 0, len1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannable.setSpan(ForegroundColorSpan(Color.BLUE), len1, len1+len2+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannable
    }
}
button.customView.tvBottom.setSpannableFactory(spannableFactory)
button.customView.tvBottom.setText("1010.2 hPa", TextView.BufferType.SPANNABLE)

我遵循了@GregotRant 的回答,它奏效了。然而,事实证明大多数 Android 设备不支持 SpannableFactory,所以我想出了另一个解决方案,灵感来自已接受的答案:

private fun setUnitTextStyle(button: CustomButton) {
        val spanText = SpannableString(button.bottomText)
        val value = spanText.split(" ")[0].length
        val unit = spanText.split(" ")[1].length

        spanText.setSpan(TextAppearanceSpan(button.context, R.style. Regular12Dark),
            value, value+unit+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        button.tvBottom.setText(spanText, TextView.BufferType.SPANNABLE)
}

Kotlin 中最干净的方法是使用 Span

val myTitleText = "1024.12hPa"

val spannable = SpannableString(myTitleText)
spannable.setSpan(
    TextAppearanceSpan(context, R.style.myFontSize),
    8, // beginning of hPa
    myTitleText.length, // end of string
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
tvMytitle.text = spannable

看我的原文post:

您可以在 kotlin 中加粗和调整字符串的一部分

val s = SpannableStringBuilder()
.append("First Part Not Bold And No Resize ")
.bold { scale(1.5f, { append("Second Part By Bold And Resize " }) } 
.append("Third Part Not Bold And No Resize")

yourTextview.text = s