position
of instantiateItem
is not actually the exact position
I assume what you mean is that position
is not the currently selected/displayed position.
It shouldn't matter what view is displaying. When user swipes from page 1 to page 2, ViewPager
loads the view for page 3 in anticipation of the next user swipe.
This is a Good Thing™. It means that the user is going to get a smoother swipe action because the view has already been inflated.
So when the ViewPager
asks your adapter for the view for page 3, then give it the view for page 3.
Now, there may be some special things you need to do when the view does become selected/displayed. In that case, you can check the answers to this question (my answer is one of them):
android - How to determine when Fragment becomes visible in ViewPager - Stack Overflow
Any solutions/workarounds ?
The solution is:
When the ViewPager
asks your adapter for a view for a certain tab, inflate that view.
When the view becomes the currently selected/displayed view, update the view as necessary.
EDIT:
The pager adapter code isn't mysterious or anything:
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
View view;
switch (position) {
case 0: // teacher
// inflate/set up your teacher view
break;
case 1: // student
// inflate/set up your student view
break;
case 2: // search
// inflate/set up your search view
break;
case 3: // chat
// inflate/set up your chat view
break;
default:
throw new IllegalArgumentException("I don't know how to set up tab " + position);
}
container.addView(view);
return view;
}
});
This really shows what @Serhio was trying to say: You don't need to know which view the ViewPager
currently has displayed; when it asks your adapter for a view, you just give it the view it wants.
And BTW, when you inflate a view inside the pager adapter, make sure you use container
as the parent:
view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp_list, container, false);