2014-01-14 22 views
2

我有問題試圖根據第一個字符在每一行上設置不同的顏色。這是我目前擁有的。沒有任何東西在textview中填充。在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); 
} 
+0

要確切地說出你正在經歷的行爲與你正在瞄準的行爲有點難。你可以進一步瞭解更多細節嗎? – Yjay

+0

什麼是listview?我沒有看到任何列表視圖。 – Houseman

回答

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中沒有任何顏色顯示出來。

相關問題