簡體   English   中英

Android如何顯示SD卡中的文本文件並一一顯示文本

[英]Android how i can display the text file from sd card and display the text one by one

我的SD卡上有一個文本文件,其中包含以下數據:

Farhan shah
Noman Shah
Ahmad shah
Mohsin shah
Haris shah

我的應用程序中有一個TextView ,現在我要在運行我的應用程序時,我的TextView僅顯示第一個名稱“ Farhan Shah”,並在x秒后顯示“ Noman Shah”,依此類推..但是現在當我運行我的應用程序,它會讀取所有文本並顯示在我的textview中。 謝謝您的任何幫助。

這是我的代碼:

File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"test.txt");

    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
        e.printStackTrace();
    }

    t = new TextView(this);
    t = (TextView) findViewById(R.id.tv_textlist);
    t.setText(text);

發生這種情況是因為在將textview設置為內容之前,您將整個文件讀入了文本。

嘗試這樣:

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"test.txt");

//Read text from file
StringBuilder text = new StringBuilder();

BufferedReader br = new BufferedReader(new FileReader(file));
TextView t = (TextView) findViewById(R.id.tv_textlist);
Timer mTimer = new Timer();

TimerTask Next = new TimerTask() {
    @Override
    public void run() {
        try {
                    String line = br.readLine();
                    if(line!= null)
                        t.setText(line);
                    else
                        mTimer.cancel();
                } catch (IOException e) {

                }   
    }
};

mTimer.scheduleAtFixedRate(Next,100L,TimeXinMillis);

代替text.append('\\ n'); 添加一些定界符,例如text.append('|'); 之后將其拆分為字符串數組並循環遍歷

t = (TextView) findViewById(R.id.tv_textlist);
text.append('|');
String[] splitText = text.toString().split("|");
for(int i = 0; i < splitText.length; i++) {
 t.setText(splitText[i]);
}
try {
  BufferedReader br = new BufferedReader(new FileReader(file));
  String line;

  while ((line = br.readLine()) != null) {

   textnames.add(line);
      text.append(line);
      text.append('\n');
  }
       }
catch (IOException e) {

e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM