Android如何从SD卡显示文本文件并逐个显示文本

时间:2014-02-20 10:37:48

标签: android textview android-sdcard

我的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);

3 个答案:

答案 0 :(得分:1)

这是因为您在将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);

答案 1 :(得分:1)

而不是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]);
}

答案 2 :(得分:0)

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();
}