当按下按钮时,我希望文本视图中的某些文本以特定序列info 1, info 2, info 3, info 4, info 5
显示。
然而,它目前似乎是随机的:info 4, info 1, info 3, info 4
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView answerLabel = (TextView) findViewById(R.id.textView1);
Button getAnswerButton = (Button) findViewById(R.id.button1);
getAnswerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String[] answers = {
"info 1", "info 2", "info 3", "info 4", "info 5"
};
String answer = "";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(answers.length);
answer = Integer.toString(randomNumber);
answer = answers[randomNumber];
answerLabel.setText(answer);
}
});
}
}
答案 0 :(得分:1)
执行以下操作应该有效:
private String[] _answers = { "info 1", "info 2", "info 3", "info 4", "info 5" };
private int _position = _answers.length - 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView answerLabel = (TextView) findViewById(R.id.textView1);
Button getAnswerButton = (Button) findViewById(R.id.button1);
getAnswerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
answerLabel.setText(_answers[_position]);
if (_position != 0) {
_position--;
}
else {
_position = _answers.length - 1;
}
}
});
答案 1 :(得分:0)
这应该做:
private final int answerNumber = 0;
private final String[] answers = {"info 1", "info 2", "info 3", "info 4", "info 5"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView answerLabel = (TextView) findViewById(R.id.textView1);
Button getAnswerButton = (Button) findViewById(R.id.button1);
getAnswerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
answerLabel.setText(answers[answerNumber]);
answerNumber = answerNumber == answers.size() - 1? 0: answerNumber + 1;
}
});
}