I'm developing an Android app to view C-programs.I wanted to give a simple color scheme to the text which is stored in database,retrieved as string and then passed on to the textview.
The code I have written assigns green color to header file declarations and brackets,blue color is assigned to numbers,printf,scanf...red is assigned to datatypes such as int,char,float.
It is however very inefficient.Before applying this color scheme,my app was displaying the textview activity instantly.Now,depending on the length of the C-programs, it takes up to 4 to 5 seconds which is really poor performance.
what it does is,it takes one keyword at a time,then iterates the complete text of textview looking for that particular keyword only and changes its color,sets the text again. Thus,it traverses text of the entire textview 29 times as I have defined 29 keywords in String arrays( namely keywordsgreen,keywordsblue,keywordsred).
The activity's onCreate fuction contains the following code :
textView = (TextView) findViewById(R.id.textView1);
textView.setText(programtext);
textView.setBackgroundColor(0xFFE6E6E6);
//The problem starts here
String [] keywordsgreen={"#define","#include","stdio.h","conio.h","stdlib.h","math.h","graphics.h","string.h","malloc.h","time.h","{","}","(",")","<",">","&","while ","for "};
for(String y:keywordsgreen)
{
fontcolor(y,0xff21610B);
}
String [] keywordsred={"%d","%f","%c","%s","int ","char ","float","typedef","struct ","void "};
for(String y:keywordsred)
{
fontcolor(y,0xFFB40404);
}
String [] keywordsblue={"printf","scanf","\n","getch","0","1","2","3","4","5","6","7","8","9"};
for(String y:keywordsblue)
{
fontcolor(y,0xFF00056f);
}
The fontcolor fuction is as follows :
private void fontcolor(String text,int color)
{
Spannable raw=new SpannableString(textView.getText());
int index=TextUtils.indexOf(raw, text);
while (index >= 0)
{
raw.setSpan(new ForegroundColorSpan(color), index, index + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index=TextUtils.indexOf(raw, text, index + text.length());
}
textView.setText(raw);
}