如何格式化字符串,然后通过注释更改样式

时间:2018-08-09 08:21:51

标签: android spannablestring spanned

我有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%1 $ s 结束”中得到“测试testBold MyValue结束”。谁有主意?

3 个答案:

答案 0 :(得分:1)

Typeface fontBold = Typeface.createFromAsset(getAssets(), "fonts/Trebuchet_MS_Bold.ttf");
    String s = getResources().getString(R.string.error_date, "20.02.2019", "25.02.2019");
    SpannableStringBuilder spannableString = new SpannableStringBuilder(s);

    Integer first1 = null;
    Integer first2 = null;
    Integer last1 = null;
    Integer last2 = null;
    int digits = 0;
    char[] crs = s.toCharArray();
    for (int i = 0; i < crs.length; i++) {
        if (Character.isDigit(crs[i]) && digits != 8) {
            if (first1 == null) {
                first1 = i;
            }
            last1 = i;
            digits++;
            continue;
        }
        if (Character.isDigit(crs[i])) {
            if (first2 == null) {
                first2 = i;
            }
            last2 = i;
        }

    }
    spannableString.setSpan(new CustomTypefaceSpan("", fontBold), first1, last1 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new CustomTypefaceSpan("", fontBold), first2, last2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getInstance());
    builder.setTitle("test");
    builder.setMessage(spannableString);
    builder.setCancelable(false);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            getLoaderManager().destroyLoader(LOADER_SOE_BILLING_ID);
        }
    });
    android.support.v7.app.AlertDialog alert = builder.create();
    alert.show();

example

答案 1 :(得分:1)

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。首先应用所有arg注释

示例实现:

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。结果

测试 testBold myValue 结束

答案 2 :(得分:0)

如何更改此代码

val confName: ConfType.Value ="Dfered"

进入

<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>

您可以像这样使用它

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

其他样式包括:

Tags                Format
--------------------------
b, strong           Bold
i, em, cite, dfn    Italics
u                   Underline
sub                 Subtext
sup                 Supertext
big                 Big
small               Small
tt                  Monospace
h1 ... h6           Headlines
img                 Image
font                Font face and color
blockquote          For longer quotes
a                   Link
div, p              Paragraph
br                  Linefeed

结果是您无法使用getText(),您可以在the documentation中找到有关此内容的信息。