1

我制作了一个包含几行的 txt 文件。我想在不同的 textView 中显示 txt 文件的每一行。我唯一能做的就是显示 txt 文件的第一行。也许还有其他方法可以显示 sd 卡文件中的文本?

我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getTxtLine(2, R.id.textView1, txt);

 public void getTxtLine(int textLine, int resId, File txtFile){
          try {

             FileInputStream fIn = new FileInputStream(txtFile);
             BufferedReader myReader = new BufferedReader(
                     new InputStreamReader(fIn));
             String aDataRow = "";
             String aBuffer = "";

             while ((aDataRow = myReader.readLine()) != null) {
                 aBuffer += aDataRow;

                 // byte buffer into a string
                 text = new String(aBuffer);
                 TextView text1 = (TextView)findViewById(resId);
                 text1.setText(text);

             }

         } catch (Exception e) {
         }
4

2 回答 2

0

//使用 API 查找 SD 卡的目录 //不要硬编码 "/sdcard" 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');
    }
}
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);
于 2013-08-13T15:54:29.207 回答
0

我认为您应该在 xml 中定义一个 ViewGroup,即 LinearLayout、RelativeLayout,并在代码中定义新的 TextView。调用 ViewGroup 的 addView。根据您的代码:

ViewGroup mGroup;   
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mGroup = (ViewGroup)findViewById(R.id.group);
    getTxtLine(2, R.id.textView1, txt);
}

public void getTxtLine(int textLine, int resId, File txtFile){
          try {

             FileInputStream fIn = new FileInputStream(txtFile);
             BufferedReader myReader = new BufferedReader(
                     new InputStreamReader(fIn));
             String aDataRow = "";
             String aBuffer = "";

             while ((aDataRow = myReader.readLine()) != null) {
                 aBuffer += aDataRow;

                 // byte buffer into a string
                 text = new String(aBuffer);
                 TextView tv = new TextView(this);
                 tv.setText(text);
                 mGroup.addView(tv);
             }

         } catch (Exception e) {
         }
}
于 2013-08-13T19:48:55.407 回答