需要帮助来优化以下java代码。它是在textview中设置特定关键字颜色的代码。(Android应用程序)

时间:2013-07-04 19:03:27

标签: java android performance html spannable

我正在开发一个应用程序来查看C程序。我想给文本提供一个简单的配色方案,该方案存储在数据库中,检索为字符串,然后传递给textview。

我编写的代码为头文件声明和括号分配绿色,蓝色分配给数字,printf,scanf ... red分配给数据类型,如int,char,float。

然而效率非常低。在应用此配色方案之前,我的应用程序立即显示了textview活动。现在,根据程序的长度,它需要4到5秒,这实际上是性能不佳。

它的作用是,它一次只需要一个关键字,然后迭代textview的完整文本,仅查找该特定关键字并更改其颜色,再次设置文本。 因此,它遍历整个textview的文本29次,因为我在String数组中定义了29个关键字(即keywordsgreen,keywordsblue,keywordsred)。

活动的onCreate功能包含以下代码:

        textView  = (TextView) findViewById(R.id.textView1);
        textView.setText(programtext);
        textView.setBackgroundColor(0xFFE6E6E6);

        //The problem stars 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);
        }

fontcolor函数如下:

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);
    }

0 个答案:

没有答案