Get Current item ViewPageAdapter Android - android

Im searching in all internet but I dont find any REAL solution about my problem.
I have a class with a Viewpager. (Class DescripcionRutinas)
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addNumDias(numDias);
adapter.setDias(dias);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(5);
}
And I have a ViewPagerAdapter
class ViewPagerAdapter extends FragmentPagerAdapter {
private int numDias;
private int count = 0;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
ArrayList<Dia> dias;
#Override
public Fragment getItem(int position) {
OneFragmentSeries fragmento = new OneFragmentSeries();
Dia ex = dias.get(**I NEED CURRENT ITEM HERE**);
nomDia = ex.getNombre();
fragmento.setSeries((ArrayList<Serie>)((ArrayList<Dia>)WorkoutYourself.dameWorkoutYourself().dameRutina(nomRutina).getDias()).get(position).getSeries());
return fragmento;
}
I need the current item position here.
NOTE: ViewPagerAdapter is INSIDE DescripcionRutinas.
Thanks guys!

Try to use yourViewPager.getCurrentItem() it should work to get your visible pager position.
Update
onPageSelected(int currentPage) should do the stuff
dia.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int arg0) {
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageSelected(int currentPage) {
//here you get your current position
}
});

Read this documentation
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int positionCurrentPage) {
if(positionCurrentPage == 1){ // if you want the second page, for example
//Your code here
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Related

Fragment not getting refresh on swipe

I am using a viewPager for its swipe abilities to swipe between two Fragments. However I want to refresh the Fragment contents on swipe. The FragmentStatePagerAdapter does a very good job of caching so its hard to get the Fragment to reload. I've tried putting everything in the onResume method but that has no effect.
Here is my code
slideadapter=new ScreenSlidePagerAdapter(this.getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
//Not used
Log.v("TAG","onPageScrolled");
}
#Override
public void onPageSelected(int position) {
//Force the fragment to reload its data
Fragment f = slideadapter.getItem(position);
f.onResume();
}
#Override
public void onPageScrollStateChanged(int i) {
//Not used
Log.v("TAG","onPageScrollStateChanged");
}
});
mSlidingTabLayout = (SlidingTabLayout)findViewById(R.id.sliding_tabs);
mViewPager.setAdapter(slideadapter);
mViewPager.setCurrentItem(0);
mSlidingTabLayout.setViewPager(mViewPager);
you can override setUserVisibleHint method in your Fragments
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
doSomething();
}
}
Use the ViewPager.onPageChangeListener:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// get fragment by position and do whatever you want to do on fragment selection.
}
});
you can try mViewPager.setOffscreenPageLimit(1); if you want to call the onresume method everytime the fragments becomes visible
Create a BaseFragment class with a method ex. loadData (),where
Viewpager child fragments extends from this BaseFragment and override the loadData () method and do the operation.
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if (slideadapter.getFragment(position) instanceof BaseFragment) {
((BaseFragment) slideadapter.getFragment (position)).loadData ();
}
}
});
In the SlideAdapter create method called
public Fragment getFragment(int key) {
return mPageReferences.get(key);
}
private final SparseArray<Fragment> mPageReferences = new SparseArray<Fragment>();
//add created fragment refernce to this array
#Override
public Fragment getItem(int position) {
mPageReferences.put(position, fragment);
}
//remove the reference when destroy
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
mPageReferences.remove(position);
}
Hope this will help!

Android endless FragmentPagerAdapter using new adapter on swipe

I am trying to create an endless FragmentPagerAdapter , on swipe to replace the adapter with a new one, and depending on which side you swipe, a global variable to increase or decrease, so you can know on what position you are. So I have tried this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
if (mViewPager.getCurrentItem() == 0) {
// left
mViewPager.setAdapter(null);
mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(1);
MyVar.INST.position--;
} else if (mViewPager.getCurrentItem() == 2) {
// right
mViewPager.setAdapter(null);
mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(1);
MyVar.INST.position++;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
the problem is, even though I have set the offscreenPageLimit to 0, Android still caches the 3 fragment in the memory by default, so when I scroll to the right, the method inside OnPageChangeListener is not being called, therefore the global variable is not being incremented properly....
Any idea how can I fix that?
EDIT: Here is the adapter
private class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Fragment1.newInstance(MyVar.INST.position + position);
}
#Override
public int getCount() {
return 3;
}
}
So I managed to do it like this, works good
private void setAdapter() {
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
if (mViewPager.getCurrentItem() == 0) {
// left
mViewPager.removeAllViews();
//globalVariable--;
setAdapter();
} else if (mViewPager.getCurrentItem() == 2) {
// right
mViewPager.removeAllViews();
//globalVariable++;
setAdapter();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
And the adapter stays the same
private class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Fragment1.newInstance(MyVar.INST.position + position);
}
#Override
public int getCount() {
return 3;
}
The main thing that makes it work is the mViewPager.removeAllViews(); which removes the previous fragments, so it doesnt mess up.
Use the globalVariable defined in some other class, singleton for example, to know on which position you are from the start

how to get item number in view pager?

how to get current item no in viewpager.
#Override
public Object instantiateItem(ViewGroup paramView, int paramInt) {
int itemno1= getItem(pager.getCurrentItem());
int itemno2= getItem(paramInt);
Toast.makeText(context, "postition"+itemno1, Toast.LENGTH_SHORT).show();
//Toast.makeText(context, "postition"+itemno2, Toast.LENGTH_SHORT).show();
}
but this methods are not working properly.when ever i swipe front and back it gives the wrong item no..
set ViewPager.setOnPageChangeListener on your viewpager.
Some thing like this-
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
// here you will get the position of selected page
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
try like this
ViewPager.getCurrentItem();
or
pageListener = new PageListener();
ViewPager.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 update views of viewpager on swipe - android

I am using view-pager.In that I have three tabs : 1. History , 2. Main , 3. Map .
I have stopwatch into main activity.When I press the start and then after stop at that time value of the stopwatch add into the sqlite DB. And into history activity I am fetching the value of stopwatch from DB and store into the listview. It's working perfect.
But now I want the update the History activity when I swipe from the Main > History so After press the stop button,I got the last value into listview of history activity.
My question is how can I update the view on swipe the viewpager?
public class SwipeyTabsSampleActivity extends FragmentActivity {
private static final String [] TITLES = {
"HISTORY",
"MAIN",
"MAP"
};
private SwipeyTabs mTabs;
private ViewPager mViewPager;
//Handler handler=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipeytab);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mTabs.setAdapter(adapter);
mViewPager.setOnPageChangeListener(mTabs);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(3);
}
private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
SwipeyTabsAdapter, ViewPager.OnPageChangeListener {
private final Context mContext;
ViewPager viewpager;
public SwipeyTabsPagerAdapter(Context context, FragmentManager fm, ViewPager mViewPager) {
super(fm);
this.mContext = context;
viewpager = mViewPager;
//viewpager.setAdapter(this);
viewpager.setOnPageChangeListener(this);
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch (position) {
case 0:
f = History.newInstance(position);
break;
case 1:
f = Main.newInstance(position);
break;
case 2:
f = Map.newInstance(position);
break;
}
return f;
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager pager = (ViewPager) container;
View view = (View) object;
pager.removeView(view);
}
public TextView getTab(final int position, SwipeyTabs root) {
TextView view = (TextView) LayoutInflater.from(mContext).inflate(
R.layout.swipey_tab_indicator, root, false);
view.setText(TITLES[position]);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPager.setCurrentItem(position);
}
});
return view;
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int positiion) {
// TODO Auto-generated method stub
}
}
}
Add ViewPager OnPageChangeListener:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// your code here
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
This will affect the changes from one page to another page in view pager.
OnPageChangeListener pagechangelistener =new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Logger.logMessage("Called first");
pageAdapter.notifyDataSetChanged();
indicator.setCurrentItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Logger.logMessage("Called second");
}
#Override
public void onPageScrollStateChanged(int arg0) {
Logger.logMessage("Called third");
}
};
myViewPager.setOnPageChangeListener(pagechangelistener);
Use this in your page adapter.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Take one string and add the Getters and setters into your FragmentActivity class.
Like...
String HistoryFragment;
public String getHistoryFragment() {
return HistoryFragment;
}
public void setHistoryFragment(String historyFragment) {
HistoryFragment = historyFragment;
}
Then after we can access another fragment from our current fragment by calling findFragmentByTag(<tag of target fragment>).
For the more information check the link Communication between Fragments in ViewPager.
Have you tried implementing OnPageChanged`? You can capture when the user start swiping.
do pager.setOnPageChanged(new ....) and Eclipse will show you the methods you can override.
Then you can override onPageScrollStateChanged(int state)
onPageScrollStateChanged(int state){
if (state==OnPageChangeListener.SCROLL_STATE_DRAGGING){
// update here
}
}

Android ViewPager's onPageScrollStateChanged never gets called

I have extended the ViewPager class and implemented onPageChangeListener.
I use this ViewPager in conjunction with a CirclePageIndicator inside a SherlockFragment. The ViewPager contains ImageViews and TextViews, nothing fancy.
I need to do something below the ViewPager every time the Page is being changed. So, I figured I need to use the onPageScrollStateChanged and verify when the state is IDLE, or something.
The problem is that from the 3 implemented methods (onPageScrollStateChanged, onPageSelected and onPageScrolled), only onPageScrolled gets called (I checked with a log message in each method). Why is that ? Code below.
public class UninterceptableViewPager extends ViewPager implements OnPageChangeListener{
private ArrayList<TwoRowListViewAdapter> mAdaptersList = null;
private ListView mListView = null;
private ProgressBar mProgressBar = null;
public UninterceptableViewPager(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public boolean onInterceptTouchEvent(MotionEvent event)
{
getParent().requestDisallowInterceptTouchEvent(true);
return super.onInterceptTouchEvent(event);
}
public void setAdaptersList(ArrayList<TwoRowListViewAdapter> adaptersList)
{
mAdaptersList = adaptersList;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
super.onPageScrolled(position++, positionOffset, positionOffsetPixels);
if (positionOffset == 0) // FIXME
loadHistoryPage(position);
}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {}
// -------------------------------------------------------------------------------------------
// -------------- Helper Methods
// -------------------------------------------------------------------------------------------
public void setListView(ListView listview)
{
mListView = listview;
}
public void setProgressBar(ProgressBar progressBar)
{
mProgressBar = progressBar;
}
private void loadHistoryPage(int position)
{
mListView.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mListView.setAdapter(null);
mListView.setAdapter(mAdaptersList.get(position-1));
mProgressBar.setVisibility(View.INVISIBLE);
mListView.setVisibility(View.VISIBLE);
}
}
When you use PageIndicator in conjunction with the Viewpager then the onPageChangeListener of the ViewPager is not called. I don't know the reason for this but this happened when I was using both. May be cause the page indicator consumes the page change event. Instead you should set a page change listener to the PageIndicator and it will be called when the page changes. Here is how you can do this:
indicator.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected (int page)
{
//page changed
}
#Override
public void onPageScrolled (int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged (int arg0)
{
}
});
I hope this will help. Feel free to discuss.
setOnPageChangeListener is deprecated.
use addOnPageChangeListener
viewPager.addOnPageChangeListener(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) {
}
});

Categories

Resources