32

I want to get the current position of the visible view of my PagerAdapter

I didn't see an obvious function like getPosition() and I want one.

I want to add an object into its arraylist at that position, but I need to know it first

CQM
  • 42,592
  • 75
  • 224
  • 366

6 Answers6

57

You would use:

int position = mViewPager.getCurrentItem()
Flimm
  • 136,138
  • 45
  • 251
  • 267
Jona
  • 13,325
  • 15
  • 86
  • 129
  • 2
    I am using the compatibility pack, and it extends PagerAdapter, there is no getCurrentItem method either. How can I make one? http://pastebin.com/LabjNvqL – CQM Dec 20 '11 at 19:41
  • No, the oncreate only runs at the start when the page is 0, use it somewhere else when the page is not 0 and it will return that page number – Shereef Marzouk Jan 03 '12 at 05:16
  • @CQM you are using a VIewPager and you are setting it's adapter to that class, show me the class where you have an oncreate – Shereef Marzouk Jan 03 '12 at 05:17
  • 1
    okay, its there now. I had to update my compatibility pack =\ that was a very frustrating realization – CQM Jan 03 '12 at 21:49
  • @CQM would be good to share what version made it work for you and then edit the answer. – philipp Dec 12 '12 at 00:19
  • @philipp if you update all your android tools at this point, and create a new "Android project" using the ADT wizard within your IDE, then you will automatically have the proper compatibility pack within your project's libs folder – CQM Dec 12 '12 at 00:38
  • I made sure my android SDK manager tells me it's the latest version and then I made sure that is implemented. Didn't work for me. I implemented the logic in the ViewPager (see my answer). Also sounds more logic tome as the adapter is not handling the view direct. – philipp Dec 12 '12 at 01:43
  • @philipp you must copy the lib from android-sdk\extras\android\compatibility\v4 to your project. The SDK manager won't update your project. – Jona Dec 16 '12 at 00:05
25

I had this problem and could not get the getCurrentItem() methode.

I ended up getting the position from the ViewPager and not from the PageAdapter. The onPageSelected(int currentPage) methode is getting the currently displayed page.

//custom PageAdapter implementation
mAdapter = new AwesomePagerAdapter();

//Our custom view pager that extends from ViewPager
mPager = (CustomViewPager) findViewById(R.id.preview_gallery);

mPager.setAdapter(mAdapter);

// get the item that we should be showing from the intent
mCurrentPage = extra.getInt("currentIndex");

// show the item the user picked
mPager.setCurrentItem(mCurrentPage);

// listen for page changes so we can track the current index
mPager.setOnPageChangeListener(new OnPageChangeListener() {

    public void onPageScrollStateChanged(int arg0) {
    }

    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    public void onPageSelected(int currentPage) {
        //currentPage is the position that is currently displayed. 
    }

});

Doing it in the PageAdaper didn't work for me as I want to preload images that are not visible. The position that is passed instantiateItem(View collection, int position) of the PageAdapter` is the position of the next item initialized. This has nothing to do with the item that is displayed.

philipp
  • 4,133
  • 1
  • 36
  • 35
3

https://github.com/Shereef/ViewPagerPlusExpandableList/blob/master/src/net/shereef/vewpagerplusexpandablelistexample/ViewPagerPlusExpandableListActivity.java#L204

if i write after that line

    Log.i("pager",myPager.getCurrentItem()+"");

it will show in the logcat the current item page while the oncreate is being run which is always 0

noteice i have used the object for the viewpager it self not the adapter.

Shereef Marzouk
  • 3,282
  • 7
  • 41
  • 64
  • are you telling me that it always returns 0? I'm not understanding, will it tell you an accurate position? – CQM Jan 02 '12 at 22:47
  • okay, its there now. I had to update my compatibility pack =\ that was a very frustrating realization – CQM Jan 03 '12 at 21:49
  • Please choose the jona's answer as the correct one, as he answered first good luck – Shereef Marzouk Jan 04 '12 at 05:09
2

Here's an updated solution that I used myself. Since setOnPageChangeListener is now deprecated you must use addOnPageChangeListener.

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int counterPosition;
            if (position == 0 || position <= currentInventory.size()){
                counterPosition = position + 1;
            } else {
                counterPosition = position;
            }

            viewPagerHeader.setText("Prize " + counterPosition + " of " + currentInventory.size());

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

The implementation above displays the correct index in my TextView so that positions 0 and the last item in the listcurrentInventory.size() display correctly. Hope this helps someone looking for an updated solution.

Phil Culver
  • 75
  • 2
  • 8
0

Try this:

  imageSlider.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
                        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
                        override fun onPageSelected(position: Int) {Log.d(TAG, "Page No.: $position")}
                        override fun onPageScrollStateChanged(state: Int) {}
                    })
Biplob Das
  • 2,818
  • 21
  • 13
0

I just faced this problem yesterday. I needed to start playing an animation in each page when the page is visible to the user and not before.

My adapter inherits from PagerAdapter and I found out that there is a function setPrimaryItem() which is triggered every time a page is shown to the user as the current page.

Called to inform the adapter of which item is currently considered to be the "primary", that is the one show to the user as the current page. This method will not be invoked when the adapter contains no items.

Not only you have a callback for when the page is visible but this callback also provides the position of the current page.

class MyAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        ...
    }

    @Override
    public boolean isViewFromObject(@NonNull @NotNull View view, @NonNull @NotNull Object object) {
        ...
    }

    @Override
    public void setPrimaryItem(@NonNull @NotNull ViewGroup container, int position, @NonNull @NotNull Object object) {
        super.setPrimaryItem(container, position, object);

        // `position` gives you the position of the current page

        // And this is how I managed to play the animation (Lottie library) when the page is visible to the user
        LottieAnimationView animation = ((ViewGroup) object).findViewById(R.id.my_animation_view);
        animation.playAnimation();
    }
}
Erik Medina
  • 335
  • 5
  • 11