Android在textView中显示txt文件的特定行
我制作了一个包含几行的txt文件。 我想在不同的文本视图中显示txt文件的每一行。 我唯一能做的就是显示txt文件的第一行。 也许还有其他方法可以显示sd卡文件中的文本 我的代码:Android在textView中显示txt文件的特定行,android,text,textview,Android,Text,Textview,我制作了一个包含几行的txt文件。 我想在不同的文本视图中显示txt文件的每一行。 我唯一能做的就是显示txt文件的第一行。 也许还有其他方法可以显示sd卡文件中的文本 我的代码: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getTxtLine(2, R.id
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) {
}
//使用API查找SD卡的目录 //不要硬编码/SD卡 文件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);
我认为应该定义一个视图组,即在xml中定义LinearLayout、RelativeLayout,在代码中定义新的TextView。调用ViewGroup的addView。根据您的代码:
不知道如何从SD卡读取文件?这里有一个例子:谢谢你的快速回复。我设法显示了txt文件的第一行。但我想,例如,在textview1中显示第一行,在textview2中显示第二行,依此类推。。所以我需要以某种方式提取txt文件的行。。或者类似的东西。谢谢,但我不能使用它,因为我必须使用一个特定的布局文件动画gif-s、youtube视频和此文本。我刚刚设法将整个文本显示到一个文本视图中,但是是否有可能将文本拆分为多个部分,例如每次它发现新行/n或String=我的文本在这里、这里和这里,并且它将在=?之后显示文本,您可以使用RegExp或Splite函数来达到您的要求。谢谢!RegExp可能就是我想要的。例如,如何提取行首和行尾之间的文本?还是在某个特殊角色之间?编辑:如何访问新字符串以将其放入特定的文本视图?PS,很抱歉成为新手,问了一些愚蠢的问题。谢谢TeeTracker,多亏了你对Splite和RegEx的提示,我成功地做了我需要的事情
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) {
}
}