我有一个包含文本的文件,每行都是独立的。
我希望先显示第一行,然后如果我按下一个按钮,第二行应该显示在TextView
中,而第一行应该消失。然后,如果我再次按下按钮,第三行应该被显示,以此类推。
我应该使用TextSwitcher
还是其他什么东西?我该如何做到这一点?
我有一个包含文本的文件,每行都是独立的。
我希望先显示第一行,然后如果我按下一个按钮,第二行应该显示在TextView
中,而第一行应该消失。然后,如果我再次按下按钮,第三行应该被显示,以此类推。
我应该使用TextSwitcher
还是其他什么东西?我该如何做到这一点?
你将它标记为 "android-assets",因此我假设你的文件在 assets 文件夹中。这里:
InputStream in;
BufferedReader reader;
String line;
TextView text;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.textView1);
in = this.getAssets().open(<your file>);
reader = new BufferedReader(new InputStreamReader(in));
line = reader.readLine();
text.setText(line);
Button next = (Button) findViewById(R.id.button1);
next.setOnClickListener(this);
}
public void onClick(View v){
line = reader.readLine();
if (line != null){
text.setText(line);
} else {
//you may want to close the file now since there's nothing more to be done here.
}
}
尝试一下这个。我无法完全验证它是否有效,但我相信这是您想要遵循的一般思路。自然地,您将希望用您在布局文件中指定的名称替换任何R.id.textView1/button1
。
另外:出于空间考虑,此处几乎没有错误检查。您需要检查您的资产是否存在,我非常确定当您打开文件进行读取时应该有一个try/catch
块。
编辑:重大错误,它不是R.layout
,而是R.id
我已经编辑了我的答案以解决问题。
以下代码应该满足您的需求
try {
// open the file for reading
InputStream instream = new FileInputStream("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
// do something with the line
} while (line != null);
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
instream.close();
}
openFileInput()
ж–№жі•пјҹжӯӨеӨ–пјҢдҪ еә”иҜҘе§Ӣз»ҲдҪҝз”ЁвҖңtry/finallyвҖқеқ—жқҘе…ій—ӯжөҒпјҲиҝҷж ·е®ғ们еңЁжҠӣеҮәејӮеёёж—¶е°ұдјҡиў«е…ій—ӯпјүгҖӮ - Lukas Knuthif (instream)
和 while ( line = buffreader.readLine() )
需要替换为类似于 if (instream != null)
和 while( buffreader.hasNext() )
的内容。 - epochengine