我正在尝试根据每行的第一个字符设置不同的颜色,但遇到了问题。这是我目前的代码,但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);
}