Skip to content
Advertisement

Getting the string from the server side and separating the code fragment from the string in Kotlin

I made an Android application where the users ask questions, but they may use programming codes in their questions. How can I separate the programming codes from the normal texts in Kotlin? If you can explain, I want to change the background of the codes. Like this enter image description here

Advertisement

Answer

just use something just like stackoverflow i.e. put code between ““`” and you can easily parse it from string.

More info: to parse string you can use Regex

here’s some sample code that detects ““`” and changes inner text to red:

...
onCreate(){
textView.setText(formatString("alo ```alo```"));
}
...
SpannableStringBuilder formatString(String message) {
        Pattern p = Pattern.compile("(```)(.*?)(```)");// detects the pattern ```*``` in the string
        Matcher matcher = p.matcher(message);

        SpannableStringBuilder spannable = new SpannableStringBuilder(message);
        //for changing color of text
        while (matcher.find()) {
            ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
            spannable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            spannable.replace(spannable.getSpanStart(span), spannable.getSpanStart(span) + 3, "");
            spannable.replace(spannable.getSpanEnd(span) - 3, spannable.getSpanEnd(span), ""); //to remove ``` from string

        }
        return spannable;
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement