Answer the question
In order to leave comments, you need to log in
How to create a button that cycles through the elements of an array?
There are the following elements and their purposes (I won’t give the whole code, I think everything is clear anyway):
private Button next_button;
private TextView mQuestionTextView;
private int mCurrentIndex = 0;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_ocean, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true)
};
<b>private void updateQuestion() {
if (mCurrentIndex != -1) {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
} else {
throw new ArrayIndexOutOfBoundsException("ArrayIndexOutOfBoundException");
mQuestionTextView.setText(arrayExc);</b>
Далее в методе onCreate это происходит так:
Button mPrevButton = (Button)findViewById(R.id.prevButton);
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
}
});
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
, without if/else. in the updateQuestion method. mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length
; and the othermCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
does not work.
Answer the question
In order to leave comments, you need to log in
Everything works only for an array element > 0, otherwise, of course, an ArrayIndexOutOfBoundsException appears
public void onClick(View v) {
mCurrentIndex--;
if (mCurrentIndex == -1) {
mCurrentIndex = mQuestionBank.length - 1;
}
updateQuestion();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question