在textview中逐行显示文件内容

时间:2015-07-09 11:15:00

标签: java android multithreading textview sleep

我有以下代码:我想在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工作正常但文本视图未显示。

2 个答案:

答案 0 :(得分:0)

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



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




答案 1 :(得分:0)

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

一个简单的解决方案可能是引入一个布尔值或(甚至更简单地)检查你的'行'不是空...

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

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

                Thread.sleep(200) //let other processes have some cpu
                }
            });
        }
    });
不要忘记让你的String行成为你的类的成员,这样你的Runnable就可以访问它...

private String line = null;