0

我想在被(*)包围时制作文本,它会是粗体,被(〜)包围它会是罢工。我按照此链接并将代码修改为这样

text = "*~TEST~* *TEST* ~TEST~ TEST";
texview.setText(createSpannable(text))

private static SpannableStringBuilder createSpannable(final String str) {
        StringBuffer stringBuffer = new StringBuffer();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();

        //Matcher matcher = BOLD_REGEX.matcher(str);
        Matcher matcher = Pattern.compile("(\\*(.*?)\\*)|(~(.*?)~)").matcher(str); //BOLD | STRIKE
        while (matcher.find()) {
            String group = matcher.group();

            stringBuffer.setLength(0);


            if (BOLD_REGEX.matcher(group).matches()) {//(\*(.*?)\*)
                String spanText = group.substring(1, group.length() - 1);
                matcher.appendReplacement(stringBuffer, spanText);
                spannableStringBuilder.append(stringBuffer.toString());
                int start = spannableStringBuilder.length() - spanText.length();
                spannableStringBuilder.setSpan(new StyleSpan(BOLD), start, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                if (STRIKE_REGEX.matcher(spannableStringBuilder).matches()) {
                    createSpannable(spannableStringBuilder.toString());
                }
            }

            if (STRIKE_REGEX.matcher(group).matches()) {//(~(.*?)~)
                String spanText1 = group.substring(1, group.length() - 1);
                matcher.appendReplacement(stringBuffer, spanText1);
                spannableStringBuilder.append(stringBuffer.toString());
                int start1 = spannableStringBuilder.length() - spanText1.length();
                spannableStringBuilder.setSpan(new StrikethroughSpan(), start1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                if (BOLD_REGEX.matcher(spannableStringBuilder).matches()) {
                    createSpannable(spannableStringBuilder.toString());
                }
            }
        }

        stringBuffer.setLength(0);
        matcher.appendTail(stringBuffer);
        spannableStringBuilder.append(stringBuffer.toString());

        return spannableStringBuilder;
    }

期望输出:

期待

我的输出:

我的输出

我怎样才能做到这一点?

4

0 回答 0