0

Suppose there is an array of objects that displays content on the screen. They are kept in an array that is normally navigated via a Next and Previous button. Normally, the buttons just add or subtract one to the increment variable depending on whether the next or previous button is pressed.

If the user selects "Random," the counter variable is set to a random number each time the Next button is pressed, so random objects are displayed. Is there an easy way to wire up the Previous button in that situation?

I'm working with Java for an Android App.

1

3 Answers 3

0

Sounds to me like you need to keep a history of indices visited since users could easily press the Next and Random buttons in an unpredictable order. Use an ArrayList or similar data structure and add the new index to the list every time the Next or Random button is pressed. Then the Previous button simply has to retrieve (and remove) the last index in the list.

0

You would have to keep track of each array position generated by the random function.

You could create a LinkedList to hold each array-index value that is being displayed.

something like:

LinkedList<Integer> indexOrder = new LinkedList<Integer>();

// Each time you access a random index in the array, store it in the list:
indexOrder.add(rand);

Then when you want to get the previous element you can iterate backwards through the list using the descendingiterator.

Iterator<Integer> iterator = indexOrder.descendingiterator();
// Then to iterate through the previous objects in your content-array:
while(iterator.hasNext()){
    Object previousObject = contentArray[iterator.next()];
}

Of course, the first object in the iterator will be the current object being displayed, so you may want to skip that one.

You could alternatively use a Stack if you will only ever want to traverse the list in a Last-in-first-out manner.

0

Keep a previous member variable

private Object[] array;
private int counter;
private int last;
...
private View.OnClickListener mButtonNextListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        last = counter++
        Object object = array[counter];
        //do whatever
    }
};

private View.OnClickListener mButtonPreviousListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        counter = last;
        Object object = array[counter];
    }
};

A more sophisticated version would push last onto a stack with next and pop last on previous. Be sure to check that the counter value os good somewhere (or the stack isn't empty before popping)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.