通过随机生成器在文本视图中按特定顺序获取文本

时间:2015-03-06 16:18:57

标签: android eclipse

当按下按钮时,我希望文本视图中的某些文本以特定序列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);

            }
        });

    }

}

2 个答案:

答案 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;
        }
    });
}