2

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

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

但是效率很低。在应用这种配色方案之前,我的应用程序会立即显示 textview 活动。现在,根据程序的长度,它需要 4 到 5 秒,这确实是性能很差。

它的作用是,一次取一个关键字,然后迭代 textview 的完整文本,仅查找该特定关键字并更改其颜色,再次设置文本。因此,它遍历整个文本视图的文本 29 次,因为我在字符串数组中定义了 29 个关键字(即关键字绿色、关键字蓝色、关键字红色)。

活动的 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);
        }

字体颜色函数如下:

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

0 回答 0