How to Get the Current Page Number of a Viewpager for Android

How do you get the current page number of a ViewPager for Android?

in the latest packages you can also use

vp.getCurrentItem()

or

vp is the viewPager ,

pageListener = new PageListener();
vp.setOnPageChangeListener(pageListener);

you have to put a page change listener for your viewPager. There is no method on viewPager to get the current page.

private int currentPage;

private static class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
Log.i(TAG, "page selected " + position);
currentPage = position;
}
}

How to get the current 'page number' from a ViewPager, fragment set up, correctly in Java for Android Development

You are getting those wrong numbers because the ViewPager instantiates the fragments surrounding the current one, in order to get a smooth swipe. Using setOffScreenPageLimit(int) you set the number of pages that should be retained to either side of the current page. The default is 1. Also note that the ViewPager first position is 0, not 1.

  1. When you set the ViewPager's adapter and it shows the first page (position=0), the fragment of the second page is also created while the current page position is still 0.
  2. You swipe to the page 2 and the third fragment is created while the current page position is 1.(There is now one exisiting instance to each side of the current one)
  3. swipe to page 3 and the fourth fragment is created showing the current page position, which is now 2. (page 1 fragment is destroyed)
  4. Swipe to page 4 and the last fragment is created while the current page position is 3. (page 2 is destroyed)
  5. Swipe to the page 5 (page 3 is destroyed)

The same when you scroll back, page 5 and page 4 already exist, showing wrong positions 3 and 2, when you swipe back to page 4, fragment in page 3 is created while current position is 3, and so on.

To get the page position. Just like Ramy mentioned, you can get the position from the PagerAdapter's getItem() and pass it as an argument to each instance of UserFragment.

public Fragment getItem(int position) {
UserFragment fragment = new UserFragment();
Bundle args = new Bundle();
args.putInt("page_position", position + 1);
fragment.setArguments(args);
return fragment;
}

Then, you can get the position in UserFragment like this:

TextView tv = (TextView) rootView.findViewById(R.id.avg_testtv);
tv.setText(String.valueOf(getArguments().getInt("page_position")));

edit

Try this way:

public Fragment getItem(int position) {
UserFragment fragment = fragments.get(position);
Bundle args = new Bundle();
args.putInt("page_position", position + 1);
fragment.setArguments(args);
return fragment;
}

Android ViewPager get the current View

I've figured it out. What I did was to call setTag() with a name to all Views/ListViews, and just call findViewWithTag(mytag), mytag being the tag.

Unfortunately, there's no other way to solve this.

Save the number of the current page of ViewPager

After you have initialised your viewpager, use this method :

viewPager.setCurrentItem(int position)

Or this :

viewPager.setCurrentItem(int position, boolean withAnimation)

You can save the last position by using SharedPreference in the onPageSelect() method where you can get the position of each page. You have to implement the OnPageChangeListner in order to have this method.

Edit

Your question wasn't clear :

Sorry, maybe I didn't express my problem well enough. I want the starting page to appear everytime I start my app. But if I enter the activity by the back-button (for example if I opened my settings activity and then go back) the last viewed page should be shown. The solution provided in the link will lead to the safed page everytime I open the app

I don't know why you want to change this, it's a normal behavior, read this.
But if you insist, you can always use setCurrentItem() method in the onResume of your Activity/Fragment, thus the first page will always be shown after your Activity/Fragment gets resumed.

Edit 2

That can still be done by setCurrentItem. In your adapter, try to detect the index of the page of the current day. Create a method that returns that field from outside the adapter. And then after you have initialised your ViewPager,

viewpager = (ViewPager) findViewById(R.id.viewpager);
viewpager.setAdapter(adapter);
setCurrentItem(adapter.getCurrentDayPosition()) // or something like that ...

The method in the adapter :

public int getCurrentDayPosition() {
return this.currentDayPosition // this a field of the adapter.
}

Getting current view from ViewPager

You can try something like this -

@Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater;
if(position != 10){
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
itemView.setTag("View"+position);

} else {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.results, container,
false);
}
container.addView(itemView);
return itemView ;
}

And when you need the current view-

View myView = pager.findViewWithTag("View"+pager.getCurrentItem());

How to find the last page in a view pager. Or the total 'number' of views. Android Development

You should be using ViewPager.getAdapter().getCount() The getAdapter() method returns the object that supplies the pages for the ViewPager.

Android How can I have a ViewPager where the number of pages is determined by ASyncTask

I appear to have got this working in a very basic state.

DataManager
I have a DataManager which is responsible for getting the items from the server using a ASyncTask

  • it contains a list of the items returned from the server
  • it contains the ASyncTask that goes to the server to get the items, when the task completes the list of items is updated
  • it contains a "getSize()" method to return the size of the list of items
  • it has a "getItem(int position)" method which returns the item at the given position
  • it has an "isItemAvailble(int position)" method, if the item at the given index is not in the list of items, the task is called again to get the next batch of items
  • it has a DataSetObservable so that the manager can inform any observers when its data changes (i.e. when a task has completed and its items updated)

PagerAdapter

The PagerAdapter is as follows

class MyPageAdapter extends FragmentPagerAdapter {

// Members
....
private DataManager dataManager;

// create an observer to listen for changes in the data manager
private final DataSetObserver observer = new DataSetObserver() {
@Override
public void onChanged() {
Toast.makeText(appCtx(), "MyPagerAdapter observer's onChanged called", Toast.LENGTH_LONG).show();
// Notify observers on this adapter that item list has changed.
notifyDataSetChanged();
}

};

// constructor
public MyPageAdapter(DataManager dataManager, .....) {
super(fm);
this.dataManager = dataManager;
dataManager.registerDataSetObserver(observer);
}

/**
* Get the number of items from the manager
*/
private int getSize() {
return dataManager.size();
}

// get the item for the given position
@Override
public Fragment getItem(int position) {
// if the next item is not available the managers task will get the next batch
dataManager.ensureItemAvailable(position+1);

// get this position's item from the data manager and create a fragment using that item
Object obj = dataManager.getItem();
return MyPagerFragment.newInstance(obj);
}
....
....
}

Getting the current position of a ViewPager

Create a listener and set it on your viewpager:

/**
* Get the current view position from the ViewPager by
* extending SimpleOnPageChangeListener class and adding your method
*/
public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {

private int currentPage;

@Override
public void onPageSelected(int position) {
currentPage = position;
}

public final int getCurrentPage() {
return currentPage;
}
}

Get active page in ViewPager and update content

You can use the same approach from my other answer here.

Keep an array of video view references in the ViewPager adapter, so that you can start the video currently being shown, and pause any video views that are instantiated but not currently shown.

Changes to the adapter:

public class MyViewPagerAdapter extends PagerAdapter {

private LayoutInflater layoutInflater;

//Added:
public TextureVideoView[] videoViews = new TextureVideoView[videos.size()];

public MyViewPagerAdapter() {

}

@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View view = layoutInflater.inflate(R.layout.video_layout, container, false);

Video video = videos.get(position);

TextureVideoView videoView = (TextureVideoView) view.findViewById(R.id.videoView);

Uri videoUri = Uri.parse(video.getUrl());

videoView.setVideoURI(videoUri);
videoView.setMediaController(null);
videoView.requestFocus();

container.addView(view);

//Added:
videoViews[position] = videoView;

return view;
}

//.............
}

Then, outside of the adapter, use a ViewPager.OnPageChangeListener to start the current video, and pause the ones on either side:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

@Override
public void onPageSelected(int position) {

for (int i = 0; i < videos.size(); i++) {
TextureVideoView videoView = myViewPagerAdapter.videoViews[i];
if (videoView == null) continue;
if (i == position) {
videoView.start();
} else {
videoView.stop();
}
}
}

@Override
public void onPageScrollStateChanged(int state) { }
});


Related Topics



Leave a reply



Submit