我正在尝试构建一个应用程序,每次按下按钮时都会显示一个随机文本文件。我已经想出了如何从资产文件夹中获取单个文本文件,但我无法弄清楚如何让应用程序随机选择一个。我需要添加什么才能允许这样做?
我对这个有点陌生,并且一直试图找到一个解释,但到目前为止没有运气。
public class MainActivity extends AppCompatActivity {
Button random_story;
TextView story_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random_story = (Button) findViewById(R.id.random_story);
story_text = (TextView) findViewById(R.id.story_text);
random_story.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = "";
try {
InputStream is = getAssets().open("1.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex){
ex.printStackTrace();
}
story_text.setText(text);
}
});
}
}
目前代码总是得到“1.txt”。资产文件夹包括 1、2、3、4、5 等,我希望按下按钮随机选择其中之一。
生成一个随机并使用它
Random r = new Random();
int fileStart = 1; // if first file name is 1.text
int fileEnd = 11; // if last file name is 10.txt
int randomFile = r.nextInt(fileEnd - fileStart) + fileStart;
现在使用它
InputStream is = getAssets().open(randomFile + ".txt");
注意:此解决方案仅在文件名按顺序排列时才有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句