Andrei
Andrei

Reputation: 137

Android ViewPager position not working correct

I have a viewpager and some images setted on click above the viewpager. The problem is that I setted the images onclick according to the viewpager position. It works fine, but the problem is that if I start the application, and click one of the images, it shows what it should show when the position is 1, but if I scroll to the 2nd image and then scroll back to the first, the position is not anymore correct, and it remains the 2nd position. How can I clear the position after each scroll to make it get the position correct? Thanks !

MainActivity.java:

package com.descoper.rom;

import java.io.IOException;

import android.app.Activity;
import android.app.Dialog;
import android.app.WallpaperManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
    private int currentPage;
    private static int NUM_VIEWS = 53;
    Dialog dialog;
    private MyPagerAdapter adapter;
    private ViewPager pager;
    private int[] pics = { R.drawable.casapoporului2, R.drawable.transfagarasan,
            R.drawable.transalpina, R.drawable.balealac,
            R.drawable.barajulsiriu, R.drawable.bisericadesublac,
            R.drawable.canionulscari, R.drawable.cascadacailor,
            R.drawable.cascadaciucas, R.drawable.castelulbran,
            R.drawable.castelulcorvinilor, R.drawable.castelulkaroly,
            R.drawable.castelulpeles, R.drawable.castelulsturdza,
            R.drawable.castelulhuniazilor, R.drawable.castrulroman,
            R.drawable.cazaneledunarii, R.drawable.cazinoulconstanta,
            R.drawable.cetateabastionara, R.drawable.cetateafagaras,
            R.drawable.cetateaprejmer, R.drawable.cheilebicazului,
            R.drawable.cheileturzii, R.drawable.centrulvechi,
            R.drawable.cimitirulsapanta, R.drawable.colibita,
            R.drawable.deltadunarii, R.drawable.epavacostinesti,
            R.drawable.focurilevii, R.drawable.hanulancutei,
            R.drawable.insulaovidiu, R.drawable.laculalbastru,
            R.drawable.laculana, R.drawable.laculbeului,
            R.drawable.laculbucura, R.drawable.laculcapra,
            R.drawable.laculrosu, R.drawable.laculvidra,
            R.drawable.laculvulturilor, R.drawable.mocanita,
            R.drawable.parculcraiova, R.drawable.parcultimisoara,
            R.drawable.pesteraghetarul, R.drawable.pesteraursilor,
            R.drawable.piatabrasov, R.drawable.poduldumnezeu,
            R.drawable.salinapraid, R.drawable.salinaturda,
            R.drawable.shighisoara, R.drawable.sarmisegetuzaregia,
            R.drawable.sfinxulbucegi, R.drawable.sibiu,
            R.drawable.vulcaniinoroiosi };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        adapter = new MyPagerAdapter();
        pager = (ViewPager) findViewById(R.id.myviewpager);
        pager.setAdapter(adapter);

        PagerTitleStrip pagerTitleStrip = (PagerTitleStrip) findViewById(R.id.titlestrip);

    }

    private class MyPagerAdapter extends PagerAdapter {

        protected static final int SCREEN_WIDTH = 0;
        protected static final int SCREEN_HEIGHT = 0;
        String[] title = { "Casa poporului", "Transfagarasan", "Transalpina",
                "Balea Lac", "Barajul Siriu", "Biserica de sub lac",
                "Canionul Sapte scari", "Cascada Cailor", "Cascada Ciucas",
                "Castelul Bran", "Castelul Corvinilor", "Castelul Karoly",
                "Castelul Peles", "Castelul Sturdza", "Castelul Huniazilor",
                "Castelul Roman", "Cazanele Dunarii", "Cazinoul din Constanta",
                "Cetatea Bastioara", "Cetatea Fagaras",
                "Biserica fortificata de la Prejmer", "Cheile Bicazului",
                "Cheile Turzii", "Centrul istoric din Bucuresti",
                "Cimitirul vesel din Sapanta", "Lacul Colibita",
                "Delta Dunarii", "Epava din Costinesti", "Focurile Vii",
                "Hanul Ancutei", "Insula Ovidiu", "Lacul Albastru",
                "Lacul Sfanta Ana", "Lacul ochiul Beiului", "Lacul Bucura",
                "Lacul Capra", "Lacul Rosu", "Lacul Vidra", "Lacul Vulturilor",
                "Mocanita din Maramures", "Parcul Nicolae Romanov din Craiova",
                "Piata Operei din Timisoara", "Pestera Scarisoara",
                "Pestera Ursilor", "Piata Sfatului din Brasov",
                "Podul lui Dumnezeu", "Salina Praid", "Salina Turda",
                "Cetatea Sighisoara", "Cetatea Sarmizegetusa",
                "Sfinxul din Bucegi", "Piata mare din Sibiu",
                "Vulcanii Noroiosi" };

        @Override
        public CharSequence getPageTitle(int position) {
            return title[position];
        }

        @Override
        public int getCount() {
            return NUM_VIEWS;
        }

        /**
         * Create the page for the given position. The adapter is responsible
         * for adding the view to the container given here, although it only
         * must ensure this is done by the time it returns from
         * {@link #finishUpdate()}.
         * 
         * @param container
         *            The containing View in which the page will be shown.
         * @param position
         *            The page position to be instantiated.
         * @return Returns an Object representing the new page. This does not
         *         need to be a View, but can be some other container of the
         *         page.
         */
        @Override
        public Object instantiateItem(View collection, final int position) {
            ImageView view = new ImageView(MainActivity.this);
            view.setImageResource(pics[position]);




            final ImageView img4 = (ImageView) findViewById(R.id.imageView4);
            img4.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent g1 = new Intent(MainActivity.this, Galerie.class);
                    startActivity(g1);

                }
            });

            final ImageView img6 = (ImageView) findViewById(R.id.imageView6);
            img6.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent r = new Intent(MainActivity.this, Romania.class);
                    startActivity(r);

                }
            });

            final ImageView img3 = (ImageView) findViewById(R.id.imageView3);
            img3.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    WallpaperManager myWallpaperManager = WallpaperManager
                            .getInstance(getApplicationContext());

                    Display display = getWindowManager().getDefaultDisplay();
                    Point size = new Point();
                    display.getSize(size);
                    int width = size.x;
                    int height = size.y;

                    myWallpaperManager.getDesiredMinimumWidth();
                    myWallpaperManager.getDesiredMinimumHeight();

                    try {
                        myWallpaperManager.setResource(position);
                        Toast.makeText(getApplicationContext(),
                                "Wallpaper-ul a fost setat cu succes!",
                                Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            });

            final ImageView img2 = (ImageView) findViewById(R.id.imageView2);
            img2.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    switch (position) {
                    case 1:
                        Intent m1 = new Intent(MainActivity.this, Maps.class);
                        startActivity(m1);
                        break;
                    case 2:
                        Intent i2 = new Intent(MainActivity.this, Romania.class);
                        startActivity(i2);
                        break;

                    default:
                        break;
                    }

                }
            });

            final ImageView img = (ImageView) findViewById(R.id.imageView1);
            img.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    switch (position) {
                    case 1:
                        dialog = new Dialog(MainActivity.this);
                        dialog.setContentView(R.layout.dialog1);


                        Button btnSave = (Button) dialog
                                .findViewById(R.id.button1);

                        btnSave.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();

                            }
                        });
                        dialog.show();

                        break;
                    case 2:
                        Intent i2 = new Intent(MainActivity.this, Romania.class);
                        startActivity(i2);
                        break;

                    default:
                        break;
                    }

                }
            });

            final ImageView img5 = (ImageView) findViewById(R.id.imageView5);
            img5.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setType("message/rfc822");
                    i.putExtra(Intent.EXTRA_EMAIL,
                            new String[] { "[email protected]" });
                    i.putExtra(Intent.EXTRA_SUBJECT, "");
                    i.putExtra(Intent.EXTRA_TEXT, "");
                    try {
                        startActivity(Intent
                                .createChooser(i,
                                        "Trimite-mi un email cu parerea ta. Multumesc !"));
                    } catch (android.content.ActivityNotFoundException ex) {
                    }

                }
            });

            ((ViewPager) collection).addView(view, 0);

            return view;
        }

        /**
         * Remove a page for the given position. The adapter is responsible for
         * removing the view from its container, although it only must ensure
         * this is done by the time it returns from {@link #finishUpdate()}.
         * 
         * @param container
         *            The containing View from which the page will be removed.
         * @param position
         *            The page position to be removed.
         * @param object
         *            The same object that was returned by
         *            {@link #instantiateItem(View, int)}.
         */
        @Override
        public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((ImageView) view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        /**
         * Called when the a change in the shown pages has been completed. At
         * this point you must ensure that all of the pages have actually been
         * added or removed from the container as appropriate.
         * 
         * @param container
         *            The containing View which is displaying this adapter's
         *            page views.
         */
        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }



    }

    }

Upvotes: 3

Views: 3130

Answers (1)

ILovemyPoncho
ILovemyPoncho

Reputation: 2792

Try using a page change listener:

pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

        }
    });

Edit:

Note that the viewpager initial position is not 1, is actually 0. Because of that initialize the currentPage as 1:

 private int currentPage = 1;

In the pageChangeListener do this:

pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            currentPage = position + 1; 
        }
    });

Now you will use currentPage inside your onClickListeners, e.g.:

final ImageView img2 = (ImageView) findViewById(R.id.imageView2);
        img2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (currentPage) {
                case 1:
                    Intent m1 = new Intent(ScrollImageActivity.this, Maps.class);
                    startActivity(m1);
                    break;
                case 2:
                    Intent i2 = new Intent(ScrollImageActivity.this, Romania.class);
                    startActivity(i2);
                    break;

                default:
                    break;
                }

            }
        });

Upvotes: 3

Related Questions