Android : Implementation of two way Endless Viewpager - android

What I want:
I have been trying to implement two directional Endless viewpager in Android, Left to Right & Right to Left
What I did:
I have implemented Endless viewpager adapter, it works fine for right to left direction, I have set current item position by viewPager.setCurrentItem(Integer.MAX_VALUE/2);.
Reference:
Help would be appreciate.

Try to check below FragmentPagerAdapter to get endless viewpager adapter :
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return Integer.MAX_VALUE;
}
#Override
public Fragment getItem(int position) {
return getFragmentBasedOnPosition(position);
}
private Fragment getFragmentBasedOnPosition(int position) {
int fragmentPos = position % 3; // Assuming you have 3 fragments
switch(fragmentPos) {
case 0:
return Fragment1.newInstance();
case 1:
return Fragment2.newInstance();
case 2:
return Fragment3.newInstance();
}
}
}
I found solution here.
I hope its helps you.

I have made my own solution. I created a ViewPager that supports infinite looping effect, smart auto-scroll, compatible with any indicators and easy to use. It especially uses it as banners of application with a simple item page.
My custom ViewPager can:
Plug and play, easy to use
Infinite Looping items
Auto-scroll items, allow config, auto-resume/pause when activity/fragment resume/pause
Won't scroll or loop if it has only 1 item
Compatible with many indicators
Github link: https://github.com/kenilt/LoopingViewPager
Hope it helps!

One simple way to achieve this for ViewPager2 is with 3 basic ideas:
Add the first and last items of your data model collection to the end and start, respectively, of that same collection. E.g. listOf(1, 2, 3, 4, 5) should become listOf(5, 1, 2, 3, 4, 5, 1).
When setting up the pager, set it to start with index 1.
When the user scrolls to index 0, have the pager scroll instantly to the penultimate index. When the user scrolls to the last index, have the pager scroll instantly to index 1.
Some sample code to do this is as follows:
1.
private fun <T> List<T>.prepareForTwoWayPaging(): List<T> {
val first = first()
val last = last()
return toMutableList().apply {
add(0, last)
add(first)
}
}
pager.setCurrentItem(1, false)
pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
// We're only interested when the pager offset is exactly centered. This
// will help create a convincing illusion of two-way paging.
if (positionOffsetPixels != 0) {
return
}
when (position) {
0 -> pager.setCurrentItem(adapter.itemCount - 2, false)
adapter.itemCount - 1 -> pager.setCurrentItem(1, false)
}
}
})
Caveat: this code does not reconcile any TabLayout or an empty data model collection.

The proposed solutions are correct but to achieve the result you need to set the initial value of your viewpager to Integer.MAX_VALUE/2.
Anyway, I don't really like this solution, setting getCount to return Integer.MAX_VALUE can have huge impact on application performance.
I figured out a solution in order to avoid this problem using the:
onPageScrollStateChanged Listener
I simply reorder the fragment list, update the viewPager and move to the new page without animation, the result is an endless loop in both directions:
mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
Boolean first = false;
Boolean last = false;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{}
#Override
public void onPageSelected(int position)
{
if (position == 0)
{
first = true;
last = false;
}
else if (position == mainFragmentList.size() -1)
{
first = false;
last = true;
}
else
{
first = false;
last = false;
}
}
#Override
public void onPageScrollStateChanged(int state)
{
if (first && state == ViewPager.SCROLL_STATE_IDLE)
{
// Jump without animation
Fragment fragment = mainFragmentList.get(mainFragmentList.size() -1);
mainFragmentList.remove(mainFragmentList.size() -1 );
mainFragmentList.add(0,fragment);
mainPagerAdapter.setData(mainFragmentList);
mainPagerAdapter.notifyDataSetChanged();
Log.e(TAG,mainFragmentList.toString());
mainViewPager.setCurrentItem(1,false);
}
if(last && state == ViewPager.SCROLL_STATE_IDLE)
{
// Jump without animation
Fragment fragment = mainFragmentList.get(0);
mainFragmentList.remove(0);
mainFragmentList.add(fragment);
mainPagerAdapter.setData(mainFragmentList);
mainPagerAdapter.notifyDataSetChanged();
Log.e(TAG,mainFragmentList.toString());
mainViewPager.setCurrentItem(mainFragmentList.size()-2,false);
}
}
});
This is what happens here:
in this example, we have 4 fragments A-B-C-D
if the user is on fragment A (first), the new List will become: D-A-B-C
[remove the last and push as first]
I update the ViewPager and move (without animation) again to fragment A so index 1.
Now the user can continue to scroll left and will find fragment D.
Same thing with the last fragment:
starting again with A-B-C-D
if the user is on fragment D (last), the new List will become: B-C-D-A
[remove the first and push as last]
I update the ViewPager and move (without animation) again to fragment D so index mainFragmentList.size()-2.
Now the user can continue to scroll right and will find fragment A.
Remember to implement FragmentStatePagerAdapter NOT FragmentPagerAdapter

Related

Android studio - tabbed activity how to reset fragment to default view?

I have one fragment where are three (default) images and when user click on them, they will change to another. But when i swipe to another fragment and back to fragment with images there are not default ones as on the start. When I swipe two times so I will pass to another fragment (distance from original with images is 2 fragments) images are resetted to default. I was trying to implement setOffscreenPageLimit() from ViewPager and set it to 1, but minimum "length" when views in fragments are resetted is 2. How can I change that images to default manually after swipe action? Thank you.
Edit: I think that issue why onResume() is not working here: Fragment onResume not called
but i dont know what that means :/ I have three classes FragmentController.class, PagerAdapter.class and class of specific fragment for example FirstFragment.class. I don't know how connect these classes together.
Check that you create the fragments in the getItem() method of the adapter and do not hold any reference to that fragments (only WeakReferences if necessary), otherwise the fragments could not be destroyed.
EDIT:
The first fragment is unloaded only when you are in the third one because setOffscreenPageLimit is at least 1 so a viewpager allways loads the fragments that are at both sides of the selected one.
What you could do is to update your adapter with this code to provide a getFragment(position) method:
private HashMap<Integer, WeakReference<Fragment>> fragmentReferences = new HashMap<>();
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = FirstFragment.newInstance();
break;
// etc
}
fragmentReferences.put(position, new WeakReference<>(fragment));
return fragment;
}
public Fragment getFragment(int position) {
WeakReference<Fragment> ref = fragmentReferences.get(position);
return ref == null ? null : ref.get();
}
After then you can get the selected fragment and call the method you want from the first fragment when a page is selected:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int currentPage) {
if (currentPage == 0) {
Fragment firstFragment = adapter.getFragment(0);
if (firstFragment != null) {
// This method resets the images of the first fragment
((FirstFragment) firstFragment).reset();
}
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Do nothing
}
#Override
public void onPageScrollStateChanged(int state) {
// Do nothing
}
});

How do you notify a PagerAdapter that the fragments have changed when the count is the same?

I have built an application with a navbar on the left, whose main content is a ViewPager
The ViewPager slides between two different views.
When the user selects something from the navgation bar, I send a message to the ViewPager's adapter (I have tried both FragmentPagerAdapter and FragmentStatePagerAdapter for this, both won't work) which sets an internal variable and calls notifyDatasetChanged();
The problem is that the getCount() method always returns 2 , so when the adapter checks to see if the dataset has changed, it sees that the items are still 2 and does not go on to call getItem(position).
The getItem(position) returns different fragments according to the value of the internal variable that is set before notifyDatasetChanged();
I tried overriding getItemId(position) in case the pager checks for the id, but it seems to not bother after checking the count.
Is there a way to force the adapter to rebuild the fragments when notifyDatasetChanged() is called?
Thanks in advance for any help you can provide
Edit: here is the code I am currently using:
public class ContentAdapter extends FragmentPagerAdapter {
private ViewedSection _section = ViewedSection.Main;
public ContentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ViewedScreen screen = get_screen(position);
return screen == null ? null : FragmentFactory.GetFragment(get_screen(position));
}
#Override
public int getCount() {
return 2;
}
private ViewedScreen get_screen(int position) {
//code to resolve which screen will be shown according to the current position and _section
}
public void set_page(ViewedSection section) {
this._section = section;
notifyDataSetChanged();
}
}
So when the user clicks on a NavBar item, I call ((ContentAdapter)_pager.getAdapter()).set_page(section);
For this, you need to override
public int getItemPosition (Object object)
Return POSITION_UNCHANGED if you don't want to replace the fragment. Return POSITION_NONE if you want to replace the fragment. (Also, you can return a new position to move the fragment to.)
A common override is
public int getItemPosition (Object object) {
return POSITION_NONE;
}
which will just rebuild everything.

How to scroll tablayout programmatically - Android

I have created 30 scrollable tabs using tablayout.
So first three tabs are visible on screen and rest of them are invisible which can be scroll using swipe gesture.
The problem is when I am selecting last tab programmatically but it is not get visible (tab layout not get scrolled to last tab).
How can I make tablayout to scroll to last tab?
I found the solution.
First I had found the width of tablayout and scroll it's x position to width and than called the select() method of last tab.
And it works fine.
Below is the code.
mTabLayout.setScrollX(mTabLayout.getWidth());
mTabLayout.getTabAt(lastTabIndex).select();
Updated:
If above is not working you can use the below code as well, it is also working fine.
new Handler().postDelayed(
new Runnable() {
#Override public void run() {
mTabLayout.getTabAt(TAB_NUMBER).select();
}
}, 100);
write this method in your custom tablayout (Your own layout which extends tablayout). So, in future you can use this method whenever you need instad of code duplication
public void selectTabAt(int tabIndex) {
if (tabIndex >= 0 && tabIndex < getTabCount() && getSelectedTabPosition() != tabIndex) {
final Tab currentTab = getTabAt(tabIndex);
if (currentTab != null) {
this.post(new Runnable() {
#Override
public void run() {
currentTab.select();
}
});
}
}
}
If you don't want yo use CustomLayout. you can just do this
final Tab currentTab = mTabLayout.getTabAt(tabIndex);
if(currentTab != null){
mTabLayout.post(new Runnable() {
#Override
public void run() {
currentTab.select();
}
});
}
I found this solution for me:
TabLayout tabLayout = activity.getTabLayout();
tabLayout.setSmoothScrollingEnabled(true);
tabLayout.setScrollPosition(targetChannelPosition, 0f, true);
Also, if you receive this error: "Only the original thread that created a view hierarchy can touch its views.", you can use this code, in order to run on Ui thread:
// find a way to get the activity containing the tab layout
TabLayout tabLayout = activity.getTabLayout();
activity.runOnUiThread(new Runnable()
{
#Override
public void run()
{
TabLayout.Tab tab = tabLayout.getTabAt(targetChannelPosition);
tab.select();
}
});
Are you calling tab.select() before the TabLayout and its children have actually been measured and drawn? If so, your TabLayout won't animate to the selection with tab.select() (or Kayvan N's suggestion of scrollTo()). Using a Handler will probably work, but that's not an ideal solution.
Provided the layout hasn't been laid out yet, a ViewTreeObserver will allow you to move to your selected tab after the layout process is finished.
private void scrollToTabAfterLayout(final int tabIndex) {
if (getView() != null) {
final ViewTreeObserver observer = mTabLayout.getViewTreeObserver();
if (observer.isAlive()) {
observer.dispatchOnGlobalLayout(); // In case a previous call is waiting when this call is made
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
observer.removeOnGlobalLayoutListener(this);
} else {
//noinspection deprecation
observer.removeGlobalOnLayoutListener(this);
}
mTabLayout.getTabAt(tabIndex).select();
}
});
}
}
}
Please comment if you have any suggestions.
The above answer wouldn't work because first As agirardello mentioned you should not use mTabLayout.getWidth() since it doesn't return what we need (which is the position of the child you want to scroll to) and the updated solution doesn't always work because of a bug in TabLayout (reported here) but a work around is simple.
The tabs on the tabLayout are not direct children of the TabLayout so we need to go one level deeper using
((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(YOUR_DESIRED_TAB_INDEX).getRight()
the only child of tabLayout is a TabLayout.SlidingTabStrip which is also a ViewGroup and getRight() will give us the right most position of our desired tab view. Thus scrolling to that position will give us what we desire. Here is a complete code:
int right = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(4).getRight();
mTabLayout.scrollTo(right,0);
mTabLayout.getTabAt(4).select();
NOTE: Make sure you are calling these methods after the layout has been drown (like onResume and not onCreate)
Hope this helps.
new Handler().postDelayed(
new Runnable() {
#Override public void run() {
mTabLayout.getTabAt(TAB_NUMBER).select();
}
}, 100);
The code snippet below works for me
class TriggerOnceListener(private val v: View, private val block: () -> Unit) : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
block()
v.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
}
fun onCreate() {
val position = ***The tab position you want to scroll to, 29 for your case here***
tabLayout.let { it.viewTreeObserver.addOnPreDrawListener(TriggerOnceListener(it)
{ it.setScrollPosition(position, 0f, true) } ) }
}
I dived into Tab.select(), and found Android uses Tablayout.setScrollPosition() to do this scrolling. And in onCreate() the widgets have not been measured, you need to postpone the call until layout is complete.
To select the last tab, use
tabLayout.getTabAt(X).select(); where X is the last tab index
If your TabLayout is used in conjunction with a ViewPager, which is common, simply add the following in the onCreate() method in your Activity:
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout);
That some of your tabs are not being shown indicates the tabMode attribute is set to app:tabMode="scrollable".
viewpager.setItem(position) should also set the position of the tab
This solution worked for me. My situation is a little bit different though; in my case, I am using the TabLayout with a ViewPager and adding more views and calling notifyDataSetChange().
The solution is to set a callback on the observer of TabLayout and scroll when the children are actually added to the TabLayout. Here is my example:
/**
Keep in mind this is how I set my TabLayout up...
PagerAdapter pagerAdapter = new PagerAdapter(...);
ViewPager pager = (ViewPager)findViewById(...);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout)findViewById(...);
tabLayout.setupWithViewPager(pager);
*/
public void loadTabs(String[] topics) {
animateTabsOpen(); // Irrelevant to solution
// Removes fragments from ViewPager
pagerAdapter.clear();
// Adds new fragments to ViewPager
for (String t : topics)
pagerAdapter.append(t, new TestFragment());
// Since we need observer callback to still animate tabs when we
// scroll, it is essential to keep track of the state. Declare this
// as a global variable
scrollToFirst = true;
// Alerts ViewPager data has been changed
pagerAdapter.notifyOnDataSetChanged();
// Scroll to the beginning (or any position you need) in TabLayout
// using its observer callbacks
tabs.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
/**
We use onGlobalLayout() callback because anytime a tab
is added or removed the TabLayout triggers this; therefore,
we use it to scroll to the desired position we want. In my
case I wanted to scroll to the beginning position, but this
can easily be modified to scroll to any position.
*/
if (scrollToFirst) {
tabs.getTabAt(0).select();
tabs.scrollTo(0, 0);
scrollToFirst = false;
}
}
});
}
Here is my code for the PagerAdapter if you need it too lol:
public class PagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
private List<String> titles;
public PagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<>();
this.titles = new ArrayList<>();
}
/**
* Adds an adapter item (title and fragment) and
* doesn't notify that data has changed.
*
* NOTE: Remember to call notifyDataSetChanged()!
* #param title Fragment title
* #param frag Fragment
* #return This
*/
public PagerAdapter append(String title, Fragment frag) {
this.titles.add(title);
this.fragments.add(frag);
return this;
}
/**
* Clears all adapter items and doesn't notify that data
* has changed.
*
* NOTE: Rememeber to call notifyDataSetChanged()!
* #return This
*/
public PagerAdapter clear() {
this.titles.clear();
this.fragments.clear();
return this;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
int position = fragments.indexOf(object);
return (position >= 0) ? position : POSITION_NONE;
}
}
I wonder if this is answer will be relevant since its coming very late. i actually achieved it in C# using Xamarin.
tabs.GetChildAt(0).Selected = true;
viewPager.SetCurrentItem(0, true);
tab = tabLayout.getSelectedTabPosition();
tab++;
TabLayout.Tab tabs = tabLayout.getTabAt(tab);
if (tabs != null) {
tabs.select();
}
else {
tabLayout.getTabAt(0).select();
}
if you want next tab on click event then use this code its work perfactly

PagerAdapter start position

I'm using the following example to impliment my viewPager:
http://code.google.com/p/viewpagerexample/issues/list
The problem with this example is that I can't figure out how to set my starting position, the default starting position is 0. Basically I wan't to be able to control if there is an available view on its left or the right.
Is there any way to control center's View current position? is there a better way to do it?
is it possible to make it circular?
I've found a way to set it's position, which is done outside of the class:
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
awesomePager.setCurrentItem(CurrentPosition);
and it can be limited by calculating the amount of items I want to fit in to it
I have noticed that if you recreate Activity (orientation change) with ViewPager having FragmentStatePagerAdapter, then the Adapter will reuse it's Fragments. The way to stop it is:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (viewPager != null) {
// before screen rotation it's better to detach pagerAdapter from the ViewPager, so
// pagerAdapter can remove all old fragments, so they're not reused after rotation.
viewPager.setAdapter(null);
}
super.onSaveInstanceState(savedInstanceState);
}
but then after Activity recreation ViewPager alwayes opens page 0 first and setCurrentItem(CurrentPosition); doesn't work. Fix for that is changing page after delay:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(newPosition);
}
}, 100);
To start with the last fragment I did this:
PagerAdapter pagerAdapter = new PagerAdapter();
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(pagerAdapter.getCount() - 1);
I came across a problem whereby if I set the current item before I set the adapter, the first item I get back will always be the one at position 0.
Make sure you do:
awesomePager.setAdapter(awesomeAdapter);
awesomePager.setCurrentItem(CurrentPosition);
and not:
awesomePager.setCurrentItem(CurrentPosition);
awesomePager.setAdapter(awesomeAdapter);
I have an array of size more than 1000 and in dymanic viewpager I was facing leftswipe stuck on firstload. The below code solved this and resulted in smooth scroll:
#Override
onResume(){
super.onResume();
viewPager.setCurrentItem(newPosition);
}
I'm using 3 fragments and on starting my app, the second (middle) fragment will be shown by default. Just I'm using the onResume function and all works great.
#Override
protected void onResume() {
super.onResume();
m_viewPager.setCurrentItem(1);
}
Using viewPager.setCurrentItem(newPosition); shows to the user the transition from the starting page to the newPosition, to prevent that from happening and show the newPosition directly as if it was the starting point, I added false to the second parameter something like this:
int newPosition = pages.size()-1; // Get last page position
viewPager.setCurrentItem(newPosition, false); // 2nd parameter (false) stands for "smoothScroll"
I encountered same problem.
When I initialize ViewPager, the indicator position was 0.
This may depends on amount of calculating for Pager contents. I use ViewTreeObserver like below.
mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mViewPager.setCurrentItem(newPosition);
removeOnGlobalLayoutListener(mSlidingTabLayout.getViewTreeObserver(), mGlobalLayoutListener);
}
};
mSlidingLayout.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
and,
private void removeOnGlobalLayoutListener(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener listener) {
if (observer == null) return;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
observer.removeGlobalOnLayoutListener(listener);
} else {
observer.removeOnGlobalLayoutListener(listener);
}
}
In this way, also never to bother with time setting of delay.
#Override
public Object instantiateItem(ViewGroup container, int position) {
View currentPage = null;
switch(position){
case 0:
currentPage = LayoutInflater.from(context).inflate(R.layout.page0, null)
break;
case 1:
currentPage = LayoutInflater.from(context).inflate(R.layout.page1, null)
///////////// This page will be default ////////////////////
((ViewPager)container).setCurrentItem(position);
////////////////////////////////////////////////////////////
break;
case 2:
currentPage = LayoutInflater.from(context).inflate(R.layout.page2, null)
break;
return currentPage;
}

How to create carousel ViewPager?

All I want to do is a horizontal carousel in Android.
If I have 3 screens A B and C then I want my ViewPager to allow me to move like
A <-> B,
B <-> C,
C <-> A.
GTalk for Android's conversation can be switched like this.
Samsung's homescreen and application screen can be switched like this.
A B and C are fragments and I'm using an adapter that extends FragmentPagerAdapter. All the fragments will contain a webview.
I have looked here here and here but none of them seem to be doing what I want.
Can anyone guide me in the right direction?
(Cross-posting my answer from an identical StackOverflow question)
One possibility is setting up the screens like this:
C' A B C A'
C' looks just like C, but when you scroll to there, it switches you to the real C.
A' looks just like A, but when you scroll to there, it switches you to the real A.
I would do this by implementing onPageScrollStateChanged like so:
#Override
public void onPageScrollStateChanged (int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
int curr = viewPager.getCurrentItem();
int lastReal = viewPager.getAdapter().getCount() - 2;
if (curr == 0) {
viewPager.setCurrentItem(lastReal, false);
} else if (curr > lastReal) {
viewPager.setCurrentItem(1, false);
}
}
}
Note that this calls the alternate form of setCurrentItem and passes false to cause the jump to happen instantly rather than as a smooth scroll.
There are two main drawbacks I see to this. Firstly, upon reaching either end the user has to let the scrolling settle before they can go further. Secondly, it means having a second copy of all of the views in your first and last page. Depending on how resource-heavy your screens are, that may rule out this technique as a possible solution.
Note also that since the view pager doesn't let clicks go through to underlying controls until after the scrolling has settled, it's probably fine to not set up clicklisteners and the like for the A' and C' fragments.
Edit: Having now implemented this myself, there's another pretty major drawback. When it switches from A' to A or C' to C, the screen flickers for a moment, at least on my current test device.
ViewPager settings:
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new YourPagerAdapter(getSupportFragmentManager()));
//Set the number of pages that should be retained to either side of the current page.
mViewPager.setOffscreenPageLimit(1);
mViewPager.setCurrentItem(50);
FragmentPagerAdapter:
public class YourPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 100;
final int REAL_PAGE_COUNT = 3;
public YourPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
while (position > REAL_PAGE_COUNT - 1) {
position = position - REAL_PAGE_COUNT ;
}
switch (position) {
case 0:
return FirstFragment.newInstance(position);
case 1:
return SecondFragment.newInstance(position);
case 2:
return ThirdFragment.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
Implement the getItem(int position) like this:
public Fragment getItem(int position)
{
switch(position)
{
case 0:
Fragment A = new A();
return A;
case 1:
Fragment B = new B();
return B;
same for C....
}
}
you can also have a look at here: SimpleViewPager.. download the source and understand it. Hope it helps.

Categories

Resources