在textview中逐行显示文件内容

display file content line by line in textview

我有以下代码:我想在 textview 中逐行查看但是有问题,

public class Resulat2 extends Activity {
private Handler h = new Handler();
private Handler mHandler = new Handler();

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newee);
    try {
        File file2 = new File(Ppp.path);
        FileReader fileReader = new FileReader(file2);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        final ScrollView scrollview = (ScrollView) findViewById(R.id.scrollView);
        final TextView textview = (TextView) findViewById(R.id.textView10);
        final StringBuilder sb = new StringBuilder("");
        while ((line = bufferedReader.readLine()) != null){
            final String finalLine = line;
            new Thread(new Runnable() {
                public void run() {
                sb.append(finalLine);
                sb.append("\n");
                Log.d("testing5", finalLine);
                }
            }).start();
            Thread.sleep(1000);
        }


        runOnUiThread(new Runnable() {
            public void run() {
                textview.setText(sb.toString());
                textview.setMovementMethod(new ScrollingMovementMethod());
                scrollview.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollview.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
            }
        });


        fileReader.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

当我 运行 时,log.d 工作正常,但文本视图未显示。

试试这个..它可能会有帮助

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.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');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

您对 textview 的更新有一个小缺陷,它只运行一次然后就停止了...

一个简单的解决方案可能是引入一个布尔值或(甚至更简单)检查您的 'line' 是否为 null...

runOnUiThread(new Runnable() {
        public void run() {
            while(line!= null){

                textview.setText(sb.toString());
                //...

                Thread.sleep(200) //let other processes have some cpu
                }
            });
        }
    });

不要忘记让您的字符串行成为您的 class 的成员,这样您的 Runnable 就可以访问它...

private String line = null;