2014-03-03 41 views
0

我在SDcard上有一個文件 - 「file.txt」包含單獨行中的電話號碼。 我想先顯示行,然後如果我按下按鈕,第二行應顯示在TextView中,第一行應該消失。 我有代碼,只是讀取txt文件的內容,並在TextView中完全插入所有行:我怎樣才能得到.txt文件逐行讀取

當按下按鈕時,應如何將此代碼更改爲串行輸出以下行?

File sdcard = Environment.getExternalStorageDirectory(); 
    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) { 
      line = br.readLine(); 
      text.append(line); 
      text.append('\n'); 
     } 
    } 
    catch (IOException e) { 
    } 
    tv.setText(text); 

當按下按鈕時,應如何將此代碼更改爲串行輸出以下行?

回答

0

您可以將文件的內容存儲在ArrayList < String>中,然後在按下按鈕時,將TextView中的文本更改爲列表中的另一個文本。喜歡的東西:

  1. 讀文件,然後在列表存儲:在按下按鈕

    //make this a class member variable 
    List<String> numbers = new ArrayList<String>(); 
    
    while((line = br.readLine()) != null) { 
        //store each line in our list as separate entry 
        numbers.add(line); 
    } 
    
  2. 更新的TextView:

    //make this a class member variable 
    //this is being used to get the line from list 
    int currentLine = 0; 
    
    button.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         //set the text 
         tv.setText(numbers.get(currentLine)); 
    
         //increment currentLine 
         currentLine++; 
    
         //make sure we don't go beyond the number of lines stored in the list 
         //so if we reach the last index, we start from the beginning 
         if (currentLine == numbers.size()) { 
          currentLine = 0; 
         } 
        } 
    });