別の行にテキストを含むファイルがあります。
最初に行を表示したいのですが、ボタンを押すと、2行目が表示されTextView
、最初の行が消えます。次に、もう一度押すと、3 行目が表示されます。
私はTextSwitcher
何かを使用する必要がありますか?どうやってやるの?
別の行にテキストを含むファイルがあります。
最初に行を表示したいのですが、ボタンを押すと、2行目が表示されTextView
、最初の行が消えます。次に、もう一度押すと、3 行目が表示されます。
私は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
当然のことながら、レイアウト ファイルで指定した名前でany を置き換えたいと思うでしょう。
また、ここでは、スペースの都合上、エラー チェックはほとんど行われません。アセットが存在することを確認する必要があり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();
}
TextView と ButtonView を簡単に使用できます。BufferedReader を使用してファイルを読み取ると、行を 1 行ずつ読み取る優れた API が提供されます。ボタンをクリックすると、settext を使用してテキストビューのテキストを変更するだけです。
すべてのファイル コンテンツを読み取って、文字列のリスト内に配置することも検討できます。ファイルが大きすぎない場合は、これによりクリーンになる可能性があります。
よろしく、ステファン