gpt4 book ai didi

android - 如何格式化字符串然后通过注解改变样式

转载 作者:搜寻专家 更新时间:2023-11-01 09:24:30 24 4
gpt4 key购买 nike

我有 3 个字符串本地化

<string name="tests" formatted="true">Test<annotation font="bold"> testBold %1$s</annotation> end</string>
<string name="tests" formatted="true">Тест<annotation font="bold"> тестБолд %1$s</annotation> конец</string>
<string name="tests" formatted="true">Тест<annotation font="bold"> тестБолд %1$s</annotation> кінець</string>

然后我如何通过注释添加一些参数和修改的文本。我得到的最大是做这件事

CharSequence t = getResources().getString(R.string.tests, "myValue");//in this case i lose my annotation, but set my argument
//OR
CharSequence t = getText(R.string.tests);//in this case i lose my argument but get style BOLD

public SpannableString textFormattingByTags(CharSequence t) {
SpannedString titleText = new SpannedString(t);
SpannedString titleText = (SpannedString) getText(R.string.tests);
Annotation[] annotations = titleText.getSpans(0, titleText.length(), Annotation.class);
SpannableString spannableString = new SpannableString(titleText);
for (Annotation annotation : annotations) {
if (annotation.getKey().equals("font")) {
String fontName = annotation.getValue();
if (fontName.equals("bold")) {
spannableString.setSpan(new CustomTypefaceSpan("",fontBold),
titleText.getSpanStart(annotation),
titleText.getSpanEnd(annotation),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
return spannableString;
}

在第一种情况下,我在第二种情况下得到“测试 testBold MyValue 结束”,在“测试 testBold %1$s 结束”。谁有一些想法?

最佳答案

<强>1。将参数转换为注释

你的字符串:

<string name="tests" formatted="true">Test<annotation font="bold"> testBold %1$s</annotation> end</string>

变成:

<string name="tests">Test<annotation font="bold"> testBold <annotation arg="0">%1$s</annotation></annotation> end</string>

<强>2。从资源创建 SpannableStringBuilder

val text = context.getText(R.string.tests) as SpannedString
val spannableText = SpannableStringBuilder(text)

<强>3。首先应用所有参数注释

示例实现:

fun SpannableStringBuilder.applyArgAnnotations(vararg args: Any) {
val annotations = this.getSpans(0, this.length, Annotation::class.java)
annotations.forEach { annotation ->
when (annotation.key) {
"arg" -> {
val argIndex = Integer.parseInt(annotation.value)
when (val arg = args[argIndex]) {
is String -> {
this.replace(
this.getSpanStart(annotation),
this.getSpanEnd(annotation),
arg
)
}
}
}
}
}
}

传入参数:

spannableText.applyArgAnnotations("myValue")

<强>4。应用剩余的注释

spannableText.applyAnnotations()
textView.text = spannableText

<强>5。结果

Test testBold myValue end

编辑

创建了一个小库来抽象此行为 - https://github.com/veritas1/tinytextstyler

关于android - 如何格式化字符串然后通过注解改变样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51762113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com