I know this is an old question but answers available are either not working or depreciated for the newer versions of android. please provide a solution which will work in Android 5.0 and above.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.text);
String javacode="import java.util.Scanner;\n" +
"class Addigit\n" +
"{\n" +
"public static void main(String args[])\n" +
"{\n" +
"Scanner sc=new Scanner(System.in);\n" +
"System.out.println(\"enter the no..\");\n" +
"int n=sc.nextInt();\n" +
"int fd=n%10;\n" +
"int rd=n/10;\n" +
"int sd=rd%10;\n" +
"rd=rd/10;\n" +
"int td=rd%10;\n" +
"System.out.println((fd+sd+td));\n" +
"}\n" +
"}";
textView.setText(javacode);
}
how to highlight the syntax just like stackoverflow is doing with this java code or similar to what Android studio does.
Try to Use this
String javacode="Your Java Code";
Pattern pattern = Pattern.compile("float"); //Java keyword
Matcher m = pattern.matcher(javacode);
SpannableString str = new SpannableString(javacode);
while (m.find()) {
str.setSpan(new BackgroundColorSpan(Color.YELLOW), m.start(), m.end()-1, 0);
}
textView.setText(str);