Remove custom tag from a string then format its content Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Remove custom tag from a string then format its content without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need help to parse, modify and show a string on an Android App (Java language, max API level 22)

This is a example string I’m getting from an API which contains only custom tag:

<BOLD> Something <RED> went wrong </RED> </BOLD> <NEWLINE> Server unreachable </NEWLINE>

I need to remove all this custom tags then format its content based on the tags that were wrapping that substring (so I’m expeting, for example, to get “went wrong” in red color and bold). I already tried looking up for similar problems but can’t get to the final result.

The string (cleaned and formatted) will then be used to set the Text of a TextView inside a List View

Answer

One way of doing this is like this….

       String testString="<BOLD> Something <RED> went wrong </RED> </BOLD> <NEWLINE> Server unreachable </NEWLINE>"; 

       testString=testString.replaceAll("<BOLD>","<font> <b>");

        testString=testString.replaceAll("</BOLD>","</b> </font>");

        testString=testString.replaceAll("<RED>","<font color ="#FF0000">");  //#FF0000 is hex code for red color

        testString=testString.replaceAll("</RED>","</font> ");

        testString=testString.replaceAll("<NEWLINE>","<br>");

        testString=testString.replaceAll("</NEWLINE>","");

        TextView textView=findViewById(R.id.text);
        textView.setText(Html.fromHtml(testString));

Output :

enter image description here

We are here to answer your question about Remove custom tag from a string then format its content - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji