我有一个按钮,我想让它在每次用户按下时将我位于按钮上方的文本更改为随机的。我该怎么办?
我希望看起来像这样:
"你好"
按
"你为什么要按?"
按
"不要再这样做,或者......"
按
"你刚刚做过!"
即可。
即可。
即可。
这是按钮和文本的代码。
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
textChange.setText(string.textChange2);
}
}
);
答案 0 :(得分:0)
没有神奇的方法让它随机改变文本,你必须对它进行编程才能做到这一点。您将不得不创建一个响应数组,然后在按钮的代码中,告诉它循环这些响应。例如:
private String[] responseArray = {"Hello", "Why did you press?", "Don't do that Again", "You Just did!" }
private int numTimesPressed = 0
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
//note this line will cause an error if there is not enough values in the array. You would have to write a catch for this
textChange.setText(responseArray[numTimesPressed++]);
//if you want random, you'll have to change the array index you are accessing to random value between the array's bounds
}
}
);
答案 1 :(得分:0)
您肯定需要一系列字符串响应。之后,我将使用的第一种方法是使用随机数生成器,然后将其链接回您的数组。不幸的是我无法编写代码,因为我不知道确切的语法,但是在伪代码中:
string array[x]={"Hello","Why did you press?",...};//Number of string responses (in this case it's 4)
int random_number;
random_number=RandomNumberGenerator(1,x);//1 and x are the lower and upper bounds
switch (random_number)://If you don't know, switch is basically a simplified if-else system
case 1:print "Hello";
.........
根据语言的不同,您可以使用许多在线随机数生成器。希望这有帮助!
P.S:也许你想要微调你的反应,使它们更自然。例如,如果您连续获得两个相同的响应,则可能需要重新推送响应。