Hunt
Hunt

Reputation: 8425

ViewSwitcher with Next and Prev Button

I am trying to use ViewSwitcher to act like a image wizard.

I mean there will be next and previous button to change the Image in a ViewSwitcher rather then a gallery. I have taken a reference from API Demo of android sample application.

in that they have used ViewSwitcher and Gallery but i have to use Next and Prev button instead. But i dont know how to do it.

As in sample application they have used

Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);

Where ImageAdapter keeps adding new Images in a ImageView which itself residing in a ViewSwitcher. So how can i do the same with next and previous button ?

Sample App Screen

Upvotes: 0

Views: 754

Answers (1)

user
user

Reputation: 87064

If you use an ImageSwitcher this is a very simple thing to do. You'll have to replace the Gallery with your two Buttons and link them to the ImageSwitcher :

private int[] mImageIds= //.. the ids of the images to use
private int mCurrentPosition = 0; // an int to monitor the current image's position
private Button mPrevious, mNext; // our two buttons

The two buttons will have two onClick callbacks:

public void goPrevious(View v) {
    mCurrentPosition -= 1;
    mViewSwitcher.setImageResource(mImageIds[mCurrentPosition]);
    // this is required to kep the Buttons in a valid state
    // so you don't pass the image array ids boundaries 
    if ((mCurrentPosition - 1) < 0) {
        mPrevious.setEnabled(false);
    }
    if (mCurrentPosition + 1 < mImageIds.length) {
        mNext.setEnabled(true);
    }
}

public void goNext(View v) {
    mCurrentPosition += 1;
    mViewSwitcher.setImageResource(mImageIds[mCurrentPosition]);
    // this is required to kep the Buttons in a valid state
    // so you don't pass the image array ids boundaries 
    if ((mCurrentPosition + 1) >= mImageIds.length) {
        mNext.setEnabled(false);
    }
    if (mCurrentPosition - 1 >= 0) {
        mPrevious.setEnabled(true);
    }
}

You'll have to remember to disable the previous Button in the onCreate method(as we start with the first image in the array).

Upvotes: 1

Related Questions