Giuseppe
Giuseppe

Reputation: 1089

Android:ViewFlipper with onBackPressed

Ia m using ViewFlipper in my app, and to move inside the pages, I use a Button for next and capturing the onBackPressing to return back.

the behavior is the following:

1) I click on button and move to 2 page. 2) click back and code work 3) click again on the button next 4) click back and now wont work anymore

on the step 4, I can feel the vibration, so the event fire, but my viewflipper wont to go back.

Any suggestion?

Thank's

Upvotes: 0

Views: 555

Answers (2)

Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27237

Just to add something to the other answer.

Let's say we have only two views that we are flipping through, doing:

  public void onBackPressed() {

    if (mViewFlipper.getDisplayedChild() == 1) {
        mViewFlipper.setDisplayedChild(0);
     } else if (mViewFlipper.getDisplayedChild() == 0) {
        flipView.setDisplayedChild(1);
    }
}

isn't enough. As a matter of fact, it creates another problem for you. If the view is in 0 (the first), and you then press the back button, NOTHING happens. The activity doesn't exit. This is because you haven't called super.onBackPressed(). Now, adding super.onBackPressed() to the code above also creates another problem. When you flip from 1 (the second view) it goes to the first view (0) and then exits the activity, which is wrong if not for anything but for the weird animation of skipping a view while transitioning from one activity to another.

The best way to implement onBackPressed() for your activity containing a ViewFlipper is this:

  public void onBackPressed() {
    int displayedChildId = mViewFlipper.getDisplayedChild(); //get current view's number
    if (displayedChildId > 0) { //if this number is greater than 0(let's say 5)
        mViewFlipper.setDisplayedChild(displayedChildId - 1);//We then go down that number by 1. That is 5 - 1, which is 4. This happens until displayedChildId isn't greater than 0 anymore, which is then the first view. if we press back from here, we exit the activity.
    } else {
        super.onBackPressed();
    }
}

I hope this makes sense

Upvotes: 1

Jason Cheladyn
Jason Cheladyn

Reputation: 595

public void onBackPressed() {


        if (flipView.getDisplayedChild() == 1) {
            flipView.setDisplayedChild(0);

        } else if (flipView.getDisplayedChild() == 0) {
            flipView.setDisplayedChild(1);
        }

    }

This works perfectly for me. Change onBackPressed to what ever method is calling the back button.

Upvotes: 2

Related Questions