Android 隐藏/删除随机字符串?
我在stackoverflow上使用了这个问题来创建一个没有问题的随机字符串:D 有时会出现相同的字符串,这很烦人 因此,我希望字符串在每个会话中只显示一次,我已经有一个退出会话按钮,它会终止类。假设我有1-3的数字。数字2首先显示,然后是1,因为只剩下一个数字,所以只能显示3 我的下一个按钮的按钮代码。现在它会杀死这个类并重新启动它!如何更改它,使其仅显示一个新字符串Android 隐藏/删除随机字符串?,android,string,Android,String,我在stackoverflow上使用了这个问题来创建一个没有问题的随机字符串:D 有时会出现相同的字符串,这很烦人 因此,我希望字符串在每个会话中只显示一次,我已经有一个退出会话按钮,它会终止类。假设我有1-3的数字。数字2首先显示,然后是1,因为只剩下一个数字,所以只能显示3 我的下一个按钮的按钮代码。现在它会杀死这个类并重新启动它!如何更改它,使其仅显示一个新字符串 private void onButtonClick(Button clickedButton) { Intent
private void onButtonClick(Button clickedButton) {
Intent startIntent = null;
if (clickedButton.getId() == R.id.quit) {
startIntent = new Intent(this, mainmenu.class);
finish();
}
else if (clickedButton.getId() == R.id.next) {
startIntent = new Intent(this, play.class);
startActivity(startIntent);
finish();
}
if (startIntent != null) {
startIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityIfNeeded(startIntent, 0);
}
}
private void setupbutton() {
View.OnClickListener onClickHandler = new View.OnClickListener() {
public void onClick(View v) {
onButtonClick((Button)v);
}
};
Button button = (Button)findViewById(R.id.quit);
button.setOnClickListener(onClickHandler);
button = (Button)findViewById(R.id.next);
button.setOnClickListener(onClickHandler);
对索引进行随机排列,然后使用它选择序列中的下一个字符串。由于随机数生成器生成随机数,因此出现了相同的字符串!它可以在一行中多次生成相同的数字 有许多可能性,举两个例子: 将所有字符串放在一个数组中并洗牌。然后从索引1开始逐个取出元素:
List strings = new ArrayList<String>(getResources().getStringArray(R.array.myArray));
Collections.shuffle(list);
然后稍微更改一下构造函数:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
setupbutton();
if (myString == null || myString.size() == 0) {
Resources res = getResources();
myString = new ArrayList(Arrays.asList(res.getStringArray(R.array.myArray)));
}
// get a random string
int rand = rgenerator.nextInt(myString.size());
String q = myString.get(rand);
// remove the last used string from the list
myString.remove(rand);
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(q);
}
不行!获取错误。我已经有了一个随机生成的东西,我添加了String randomString=strings.getindex;strings.removeindex;并将字符串更改为MyString.Aha,那么错误是什么?你的代码是什么样子的。你有没有尽力帮助自己?我删除了添加的代码,因为我正在尝试其他功能。图像上的代码只是我课堂的一部分!谢谢。只需从上面复制一些代码,并使用常识来适应您的代码!不要从代码中截图,编辑你的问题!完成。请再次检查我的问题。
private static ArrayList<String> myString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
setupbutton();
if (myString == null || myString.size() == 0) {
Resources res = getResources();
myString = new ArrayList(Arrays.asList(res.getStringArray(R.array.myArray)));
}
// get a random string
int rand = rgenerator.nextInt(myString.size());
String q = myString.get(rand);
// remove the last used string from the list
myString.remove(rand);
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(q);
}