In my activity I have a OnPageChangeListener and view Pager implemented.
On onPageSelectedin function I call function name viewPagerHandler, when I have all the logic for single viewPager Page (Buttons, actions depended of current page etc.)
public class ActivityClass extends Activity implements ViewPager.OnPageChangeListener, View.OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
viewPager=(ViewPager)findViewById(R.id.Pager);
adapter= new
ViewPageAdapter(ActivityClass.this,list,imagesList);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
viewPager.addOnPageChangeListener(ActivityClass.this);
}
#Override
public void onClick(View v) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
this.position=position;
viewPagerHandler(viewPager.findViewWithTag(position),position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
public View viewPagerHandler(final View view, final int position){
//ALL LOGIC BUTTONS ACTIONS ETC.
view.invalidate();
return view;
}
}
public class ViewPageAdapter extends PagerAdapter{
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
final View itemView = LayoutInflater.from(mContext).inflate(R.layout.art_work_item, container, false);
itemView.setTag(position);
container.add(itemView); // edited after suggested
if(mContext instanceof ActivityClass && position==0) //The page listener in ActivityClass is trigger only when page is changed so i tried to hack it when the viewPager is instantiate for the first time
return ((ActivityClass) mContext).viewPagerHandler(itemView,position);
return itemView;
}
}
EDIT: The logic works perfectly on the first and the last item. For rest of them the view is not refreshing (however its still working, because i have buttons which changing color after clicked, when I click on them and then slide to next item and back to the previous one the color is changed so its trigger)
You are missing the line in the instantiateItem() method,
public Object instantiateItem(final ViewGroup container, final int position) {
final View itemView = LayoutInflater.from(mContext).inflate(R.layout.art_work_item, container, false);
itemView.setTag(position);
container.addView(itemView);
if(mContext instanceof ActivityClass && position==0) //The page listener in ActivityClass //is trigger only when page is changed so i tried to hack it when the viewPager is //instantiate for the first time
return ((ActivityClass) mContext).viewPagerHandler(itemView,position);
return itemView;
}
Related
I have a tabbed activity that has a spinner in its Toolbar. I need to trigger changes in the tab fragments whenever the spinner value changes.
I have so far implemented it by getting the cropsSpinner instance from the Fragment. However it's not working as needed. I am new to listeners; is there a way I can do this with Android callbacks?
ExtensionActivity.java
public class ExtensionActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
#BindView(R.id.container) ViewPager mViewPager;
#BindView(R.id.tabs) TabLayout tabLayout;
#BindView(R.id.toolbar) Toolbar toolbar;
#BindView(R.id.spinner_nav) public Spinner cropsSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extension);
ButterKnife.bind(this);
mSectionsPageAdapter = new SectionsPageAdapter(getFragmentManager());
setupViewPager(mViewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setupWithViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getFragmentManager());
adapter.addFragment(new ExtDescFragment(),"Description");
adapter.addFragment(new ExtLandPFragment(),"Land Preparation");
viewPager.setAdapter(adapter);
}
ExtDescFragment.java
public class ExtDescFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ext_desc, container, false);
ButterKnife.bind(this,view);
((ExtensionActivity)getActivity()).cropsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
CROP =((ExtensionActivity)getActivity()).cp.get(position);
Log.e("CROP",CROP);
getCropInf();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
For your additional info I suggest you let your cropperSpinner private and using list custom listener like:
interface OnCropperSpinnerSelectedListener {
void onItemSelected(int pos);
}
Then store a list of listener in ExtensionActivity:
List<OnCropperSpinnerSelectedListener> listeners;
after that write a setter method to add listener to the listener list:
void addCropperSpinnerSelectedListener(OnCropperSpinnerSelectedListener listener) {
listeners.add(listener);
}
Then, you have to implement OnItemSelectedListener in ExtensionActivity:
cropsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
for(int i = 0; i < listeners.size(); i++) {
listeners.get(i).onItemSelected(position);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Finally, when you want any Fragment to listen to spinner value changes event (Eg: ExtDescFragment), just call the method addCropperSpinnerSelectedListener() inside onCreate() of this fragment and implement your own logic.
Explain: So every time user select item on spinner, the AdapterView.OnItemSelectedListener will call onItemSelected(), here we loop through our custom listener list that have connection to fragments and call our onItemSelected(int pos) to notify all fragment.
I have a fragment, fragment A, which holds a ViewPager. The ViewPager loads different fragments which the user can swipe through "indefinitely" (I use a really high number of pages/loops to emulate this). When a user clicks on the current ViewPager fragment, then fragment A with the ViewPager is replaced by fragment B in the fragment manager. When the user returns from fragment B, the backstack is popped using popBackStackImmediate(). If the user repeats this action several times, the heap begins to fill up by about 100kb at a time until the app starts to become sloppy and malfunction as the memory fills up. I'm unsure what exactly is causing this, can anyone help?
My fragment A with the ViewPager:
public class MainFragment extends Fragment {
private MainWearActivity mMainWearActivity;
View view;
private int currentPage;
private ViewPager pager;
private ViewPagerAdapter adapter;
private LinearLayout helpIcons;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMainWearActivity = (MainWearActivity) getActivity();
adapter = new ViewPagerAdapter(this.getChildFragmentManager());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
// Scrolling menu
pager = (ViewPager) view.findViewById(R.id.watchNavPager);
pager.setAdapter(adapter);
pager.addOnPageChangeListener(adapter);
// Set current item to the middle page
pager.setCurrentItem(Consts.FIRST_PAGE);
currentPage = Consts.FIRST_PAGE;
// Set number of pages
pager.setOffscreenPageLimit(4);
// Set no margin so other pages are hidden
pager.setPageMargin(0);
return view;
}
#Override
public void onDestroyView() {
pager = null;
super.onDestroyView();
}
}
My adapter class:
public class ViewPagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
position = position % Consts.PAGES;
switch(position){
case Consts.AUDIO_POS:
return new AdapterAudioFragment();
case Consts.VOICE_POS:
return new AdapterVoiceFragment();
case Consts.MAIL_POS:
return new AdapterMailFragment();
case Consts.INFO_POS:
return new AdapterInfoFragment();
default:
return null;
}
}
#Override
public int getCount()
{
return Consts.PAGES * Consts.LOOPS; // (4 * 1000)
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {}
}
One of my fragments that the adapter loads (they are all pretty much the same):
public class AdapterAudioFragment extends Fragment {
private ImageView menuImg;
private TextView menuText;
private LinearLayout rootView;
private MainWearActivity mMainWearActivity;
private View.OnClickListener imgClickListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMainWearActivity = (MainWearActivity) getActivity();
imgClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
mMainWearActivity.replaceFragment(mMainWearActivity.getFragment(Consts.FRAG_AUDIO), Consts.FRAG_AUDIO);
}
};
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Get root view of the fragment layout
rootView = (LinearLayout) inflater.inflate(
R.layout.fragment_nav_object, container, false);
// Set the current menu image and text
menuImg = (ImageView) rootView.findViewById(R.id.fragment_image);
menuImg.setImageResource(R.mipmap.ic_audio);
menuImg.setOnClickListener(imgClickListener);
menuText = (TextView) rootView.findViewById(R.id.menuTxt);
menuText.setText(Consts.MENU_HEADER_AUDIO);
// Set the current menu selection
mMainWearActivity.setCurrentSelection(Consts.AUDIO_POS);
return rootView;
}
}
I have a feeling that the adapter's fragments are all being created but never destroyed and piling up in the heap but I can't figure out how to resolve this. Do I need to call destroyItem in the adapter and manually destroy them? Any help would be most appreciated, thanks.
Adding this to Fragment stopped leaks for me:
#Override
public void onDestroyView() {
super.onDestroyView();
viewPager.setAdapter(null);
}
Looking at the source code, the problem seems to be that when calling ViewPager#setAdapter the view will register itself as observer for the adapter. So each time onViewCreated is called your pager adapter instance will have reference of the newly created view.
There is a specific PagerAdapter for your needs - FragmentStatePagerAdapter
This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.
I have used viewpager which displays view with an image and radiobutton below. Each swipe screen is not a fragment, they are layouts which just swipe the same view with different imageview. The problem is that, I am unable to deselect the radio button which is in left and right side of the current view after i select the radio button of the current screen. If I return POSITION_NONE in getItemPosition(), it refresh the screen and radio button also deselected but the view is flickered. If i am able to call instantiateItem(), my problem is solved . But this method is called only when view is destroyed based on the setOffsetScreenPageLimit(). How can I achieved such requirements, if view pager cannot help?
Fragment:
public class AnswerImageDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
//member declaration
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strQuestion = null;
View rootView = inflater.inflate(R.layout.activity_viewpager_demo, container,
false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
intro_images = (ViewPager) rootView.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) rootView.findViewById(R.id.viewPagerCountDots);
//do some stuff
//set the adapter
mAdapter = new ViewPagerAdapter(getContext(), map);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(clickPosition);
intro_images.setOnPageChangeListener(this);
setUiPageViewController();
bus = EventBus.getDefault();
bus.register(this);
return rootView;
}
//other method
}
PagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// member declaration
public ViewPagerAdapter(Context mContext, HashMap<String, Object> map) {
//other initialization
}
#Override
public int getCount() {
return optionImages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);
final ImageView ivOption = (ImageView) itemView.findViewById(R.id.answerId); // this is used as radio button in this case
/*The code snippet is to select the answer option based on whether answer is choosen or not.
If choosen, select as default in the pop up answer.
*/
if (null != ans) {
Iterator iterator = ans.iterator();
if (ans.size() > 0) {
int value = (int) iterator.next();
if (value == position) {
ivOption.setImageResource(R.drawable.ic_radio_button_tick);
} else {
ivOption.setImageResource(R.drawable.ic_radio_button_nontick);
}
}
}
p = position;
/*The code snippet is to change the answer value based on the user selection.
This means if user choosen another answer then clear the earlier choosen answer
*/
ivOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
txtQuestion.setText(question);
txtOption.setText(optionsList.get(position));
imageView.setParseFile(optionImages.get(position));
imageView.loadInBackground();
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
LinearLayout ll = (LinearLayout) object;
/*RelativeLayout ivOption = (RelativeLayout) ll.getChildAt(2);
ImageView iv = (ImageView) ivOption.getChildAt(1);
iv.setImageResource(R.drawable.ic_radio_button_tick);*/
container.removeView(ll);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
public void refresh(ArrayList object) {
this.object = new ArrayList();
this.object.addAll(object);
this.notifyDataSetChanged();
}
I have a ViewPager which holds two fragments. one fragment contains nothing and the other fragment contains a gridview with ImageViews.
The ImageViews have a onClickListener set.
Everything works fine so far... but when i am on the fragment which contains nothing and tap somewhere the onClickListener of the other fragments gridviews imagview reacts to my click even if its elements aren't visible.
I could change my onClickListener so that it checks which fragment is shown but is that really the way i should do it ??? it feels a bit dirty
This is my FragmentStatePageAdapter
public class OwnPagerAdapter extends FragmentStatePagerAdapter{
private BackgroundImage backgroundImage = new BackgroundImage();
private Apps apps = new Apps();
private Home_Screen ac;
public OwnPagerAdapter(FragmentManager fm, Home_Screen activity) {
super(fm);
this.ac = activity;
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return backgroundImage;
}else if(position == 1) {
return this.apps;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
This is my BaseAdapter
public class AppAdapter extends BaseAdapter {
private AppLauncher launcherListener = new AppLauncher();
private ArrayList<ApplicationInfo> appList;
private Context ctx;
public AppAdapter(ArrayList<ApplicationInfo> listOfApps, Context ctx){
this.appList = listOfApps;
this.ctx = ctx;
}
#Override
public int getCount() {
return this.appList.size();
}
#Override
public Object getItem(int i) {
ImageView v = new ImageView(this.ctx);
v.setImageDrawable(this.appList.get(i).loadIcon(this.ctx.getPackageManager()));
return v;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if(view != null){
((ImageView) view).setImageDrawable(this.appList.get(i).loadIcon(this.ctx.getPackageManager()));
view.setTag(i);
return view;
}
ImageView v = new ImageView(this.ctx);
v.setImageDrawable(this.appList.get(i).loadIcon(this.ctx.getPackageManager()));
v.setScaleType(ImageView.ScaleType.CENTER);
v.setOnClickListener(launcherListener);
v.setTag(i);
return v;
}
private class AppLauncher implements View.OnClickListener {
#Override
public void onClick(View view) {
ctx.startActivity(ctx.getPackageManager().getLaunchIntentForPackage(appList.get((int) view.getTag()).packageName));
}
}
}
Thats my fragment class
public class Apps extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<ApplicationInfo>>{
private GridView gridview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getLoaderManager().initLoader(1, null, this).forceLoad();
View rootView = inflater.inflate(R.layout.fragment_apps, container, false);
this.gridview = (GridView)rootView.findViewById(R.id.apptable);
return rootView;
}
#Override
public Loader<ArrayList<ApplicationInfo>> onCreateLoader(int id, Bundle args) {
return new AppLoader(getActivity());
}
#Override
public void onLoadFinished(Loader<ArrayList<ApplicationInfo>> loader, ArrayList<ApplicationInfo> data) {
Toast.makeText(getActivity(), "Done with loading Apps", Toast.LENGTH_LONG).show();
this.gridview.setAdapter(new AppAdapter(data,getActivity()));
}
#Override
public void onLoaderReset(Loader<ArrayList<ApplicationInfo>> loader) {
}
}
While i cant find any specific cause to your problem i have to suggest a cleaner way of achieving the same result you're seeking, using an inner class just to capture click events is dirty and just unnecessary. it is quite possible that using this method will solve your problem as well.
Instead of using AppLauncher class which implements an OnClickListener and then set it manualy for each item, why not using an OnItemClickListener on the whole gridview ? it will take care of click events for each item and is specific only to items inside your gridview so you dont have to worry about any leaks like you would using inner classes.
In your fragment implement OnItemClickListener :
public class Apps extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<ApplicationInfo>>, OnItemClickListener
Then in your fragment's onCreate simply set the adapter to the gridview:
gridview.setOnItemClickListener(this);
and implement the necessary method:
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
getActivity().startActivity(getActivity().getPackageManager().getLaunchIntentForPackage(appList.get(position).packageName));
}
Now you can remove the OnClickListener logic from your gridview's adapter and it should work fine, my guess is it will also solve your problem, and even if not, hey at least you end up with a cleaner code.
Another thing i find odd about your code is that you override getItemId() yet always return 0, make sure this is the normal behaviour you're looking for since im not sure it is.
Good luck.
I would like to implement a ViewPager which uses Fragments and can be swiped in a curcular motion e.g. Page (A<-->B<-->C<-->A).
I have read a couple of posts on how this is done, e.g. returning a fake count of how many elements there are and setting the position at the start in the middle.
how to create circular viewpager?
These all seem to be based of a PagerAdapter. When I try to do a similar thing while extending FragmentPagerAdapter, as soon as I return a fakeCount of pages I get an exception when I Swipe through my Fragments, I only have 2 Fragments.
Exception: java.lang.IllegalStateException: Can't change tag of fragment.
I think this is caused as the FragmentManager thinks I am in position 2 but position 2 points to the fragment at position 0. Does anyone know how I can avoid this? I am thinking I should experiment with extending Fragmentmanager. Any examples or help with this would be greatly appreciated.
I know it is a bit late but this is how it worked for me:
I needed a circular swipe between 3 fragments, so I made those 3 and two more virtual to help me implement the page looping:
public static class FirstViewFragment extends Fragment {
// Empty Constructor
public FirstViewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_landing_1, container, false);
}
}
public static class SecondViewFragment extends Fragment {
// Empty Constructor
public SecondViewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_landing_2, container, false);
}
}
public static class ThirdViewFragment extends Fragment {
// Empty Constructor
public ThirdViewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_landing_3, container, false);
}
}
And two more virtual fragments that enabled me to swipe left from the first and right from the last. The first virtual inflates the same layout as the last actual and the last virtual the same layout as the first actual:
public static class StartVirtualFragment extends Fragment {
public StartVirtualFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_landing_3, container, false);
}
}
public static class EndVirtualFragment extends Fragment {
public EndVirtualFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_landing_1, container, false);
}
}
My Adapter:
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new StartVirtualFragment();
case 1:
if (firstViewFragment == null) {
firstViewFragment = new FirstViewFragment();
}
return firstViewFragment;
case 2:
if (secondViewFragment == null) {
secondViewFragment = new SecondViewFragment();
}
return secondViewFragment;
case 3:
if (thirdViewFragment == null) {
thirdViewFragment = new ThirdViewFragment();
}
return thirdViewFragment;
case 4:
return new EndVirtualFragment();
}
return null;
}
#Override
public int getCount() {
return 5;
}
}
And my page listener I used the onPageScrollStateChanged to set the correct page and implement the loop:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_DRAGGING) {
int pageCount = viewPager.getChildCount();
int currentItem = viewPager.getCurrentItem();
if (currentItem == 0) {
viewPager.setCurrentItem(pageCount - 2, false);
} else if (currentItem == pageCount - 1) {
viewPager.setCurrentItem(1, false);
}
}
}
});
And in the end:
viewPager.setCurrentItem(1);
Hope I helped
I have a project in the GitHub with some widgets I've created. Here it its:
https://github.com/CyberEagle/AndroidWidgets
In the following package, there are the adapters to be used with the CircularViewPager:
https://github.com/CyberEagle/AndroidWidgets/tree/master/src/main/java/br/com/cybereagle/androidwidgets/adapter
First, you will use CircularViewPager instead of ViewPager in your layout. The CircularViewPager is here: https://github.com/CyberEagle/AndroidWidgets/blob/master/src/main/java/br/com/cybereagle/androidwidgets/view/CircularViewPager.java
This ViewPager expects a WrapperCircularPagerAdapter, instead of a PagerAdapter. This wrapper is used to trick the ViewPager, making it to think there are a lot of items in the ViewPager, but it actually repeat your items to make the circular effect. So, instead of implementing either PagerAdapter, FragmentPagerAdapter or FragmentStatePagerAdapter, you will implement either CircularFragmentPagerAdapter, CircularFragmentStatePagerAdapter or CircularPagerAdapter. Then, you will wrap your adapter with the WrapperCircularPagerAdapter and set the wrapper in the CircularViewPager, instead of your adapter. Also, when it's time to notify dataset changed, you will call the notifyDatasetChanged() in the wrapper.
When implementing one of the circular adapter, you will notice that instead of implementing instantiateItem, you will have to implement instantiateVirtualItem. For the fragment's pager adapter, you will implement getVirtualItem instead of getItem. That is because I've created the concept of virtual items.
To make it clear, imagine a view pager with 4 items, giving that each item represents a music. When you go all the way to left, you will see the 4th item in the left of the first. Actually, it's a whole new item, but it's linked to the virtual item that represents the 4th music.
Another example: imagine there's only one music now. You will see the same music on the left and on the right. There're 3 items at a time, but only one virtual item.
So, as explained, the Wrapper is tricking the ViewPager, making it think that there are a lot of items. To make it more difficult for the user to reach one of the ends of the ViewPager (it'd take a long time anyway), everytime a change happens to the dataset, the ViewPager goes to the same virtual item, but to one of the real items near the middle.
One more important thing is that the CircularViewPager has the method setCurrentVirtualItem. This method calculates which real item is the nearest desired virtual item and then it uses the setCurrentItem to set it. You have also the option to use the getCurrentVirtualItem, that will return the index of the current virtual item. Notice that if you use getCurrentItem, you'll get a large index.
Well, this is it. I'm sorry for the lack of documentation of the project. I'm planning document it soon. I'm also planning to remove the need for the wrapper. Feel free to copy the code (respecting the Apache 2.0 license), to fork or even contribute to it.
**If you want to make 3 views visible at same time and make it circular**
public abstract class CircularPagerAdapter extends PagerAdapter{
private int count;
int[] pagePositionArray;
public static final int EXTRA_ITEM_EACH_SIDE = 2;
private ViewPager.OnPageChangeListener pageChangeListener;
private ViewPager viewPager;
public CircularPagerAdapter(final ViewPager pager, int originalCount ) {
super();
this.viewPager = pager;
count = originalCount + 2*EXTRA_ITEM_EACH_SIDE;
pager.setOffscreenPageLimit(count-2);
pagePositionArray = new int[count];
for (int i = 0; i < originalCount; i++) {
pagePositionArray[i + EXTRA_ITEM_EACH_SIDE] = i;
}
pagePositionArray[0] = originalCount - 2;
pagePositionArray[1] = originalCount -1;
pagePositionArray[count - 2] = 0;
pagePositionArray[count - 1] = 1;
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(final int position) {
if(pageChangeListener != null)
{
pageChangeListener.onPageSelected(pagePositionArray[position]);
}
pager.post(new Runnable() {
#Override
public void run() {
if (position == 1){
pager.setCurrentItem(count-3,false);
} else if (position == count-2){
pager.setCurrentItem(2,false);
}
}
});
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(pageChangeListener != null)
{
pageChangeListener.onPageScrolled(pagePositionArray[position],positionOffset,positionOffsetPixels);
}
}
public void onPageScrollStateChanged(int state) {
if(pageChangeListener != null)
{
pageChangeListener.onPageScrollStateChanged(state);
}
}
});
}
#Override
public int getCount() {
return count;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
public abstract Object customInstantiateItem(ViewGroup container, int position);
public void setPageChangeListener(ViewPager.OnPageChangeListener pageChangeListener)
{
this.pageChangeListener = pageChangeListener;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
int pageId = pagePositionArray[position];
return customInstantiateItem(container,pageId);
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void setFirstItem()
{
viewPager.setCurrentItem(EXTRA_ITEM_EACH_SIDE - 1);
}
}