在TextView中每行文本显示不同的颜色

3
我正在尝试根据每行的第一个字符设置不同的颜色,但遇到了问题。这是我目前的代码,但TextView中没有任何内容显示。
TextView output=(TextView) findViewById(R.id.textView1);
    File file = new File("/sdcard/file.txt");
    StringBuilder text = new StringBuilder();
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.substring(0,1).equals("r")) {
                appendColoredText(output, line, Color.RED);
            } else if (line.substring(0,1).equals("y")) {
                appendColoredText(output, line, Color.YELLOW);
            } else if (line.substring(0,1).equals("c")) {
                appendColoredText(output, line, Color.CYAN);
            } else {
                appendColoredText(output, line, Color.BLACK);
            }
            //text.append('\n');
        }
        output.setText(text);
    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

public static void appendColoredText(TextView tv, String text, int color) {
    int start = tv.getText().length();
    tv.append(text);
    int end = tv.getText().length();

    Spannable spannableText = (Spannable) tv.getText();
    spannableText.setSpan(new ForegroundColorSpan(color), start, end, 0);
}

很难准确地判断您正在经历的行为与您所期望的行为有何不同。您能详细说明一下吗? - Yjay
什么列表视图?我没有看到任何列表视图。 - user773737
1个回答

2
public void displayOutput()
{
    TextView output=(TextView) findViewById(R.id.textView1);
    output.setMaxLines(20000);
    //File sdcard = Environment.getExternalStorageDirectory();
    File file = new File("/sdcard/file.txt");
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.substring(0,1).equals("R")) {
                appendColoredText(output, line, Color.RED);
            } else if (line.substring(0,1).equals("Y")) {
                appendColoredText(output, line, Color.YELLOW);
            } else if (line.substring(0,1).equals("C")) {
                appendColoredText(output, line, Color.CYAN);
            } else {
                appendColoredText(output, line, Color.WHITE);
            }   
        }
    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

public static void appendColoredText(TextView tv, String text, int color) {
    int start = tv.getText().length();
    tv.append(text);
    int end = tv.getText().length();
    Spannable spannableText = (Spannable) tv.getText();
    spannableText.setSpan(new ForegroundColorSpan(color), start, end, 0);
    tv.append("\n");
}

这是最终为我工作的代码

我的目标是逐行读取文本文件,并根据行的第一个字符将该行分配给textview中的颜色。我在原始代码中遇到的问题是,textview中从未以任何颜色显示任何内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接