Android ViewPager with setCurrentItem not working properly - android

Trying to implement circular view pager(Pagination). In the below code snippet, the setCurrentItem method of the Viewpageris set to first position(0th index), but it always moves to the second position(1st index).
Below is the code,
ViewPagerListener.java
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int positionOfView, float positionOffset, int positionOffsetPixels) {
LogUtil.d(TAG, "START of onPageScrolled");
mPosition = positionOfView;
LogUtil.d(TAG, "COMPLETION of onPageScrolled");
}
#Override
public void onPageSelected(int position) {
LogUtil.d(TAG, "START of onPageSelected");
//LogUtil.d(TAG, "Position :" + position + ", " + "Count of pager adapter :" + (mViewPager.getAdapter().getCount() - 1));
LogUtil.d(TAG, "COMPLETION of onPageSelected");
}
#Override
public void onPageScrollStateChanged(int state) {
LogUtil.d(TAG, "START of onPageScrollStateChanged");
if (state == ViewPager.SCROLL_STATE_DRAGGING && mPosition == 5) {
LogUtil.d(TAG, "trying to move to first");
currentItemInViewPager(0); //---> This is the position where I am setting the view to move back to start position(0th index)
}
LogUtil.d(TAG, "COMPLETION of onPageScrollStateChanged");
}
});
#Override
public void currentItemInViewPager(int index) {
LogUtil.d(TAG, "START of currentItemInViewPager");
if (index == 0) {
if (getChildFragmentManager().findFragmentByTag("TAG_INTRO_FRAGMENT") != null) {
LogUtil.d(TAG, "Removed");
getChildFragmentManager().beginTransaction().remove(getChildFragmentManager().findFragmentByTag("TAG_INTRO_FRAGMENT")).commit();
}
mViewPager.setVisibility(View.VISIBLE);
mTabLayout.setVisibility(View.VISIBLE);
mPagerAdapter = new TutorialPagerAdapter(getChildFragmentManager(), this);
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager, true);
}
mViewPager.setCurrentItem(index);
LogUtil.d(TAG, "COMPLETION of currentItemInViewPager");
}
Please let me know if I am missing out anything
Thanks

Before calling this method just call mViewPager.setCurrentItem(0);

If you want to keep the animation of paging u will need to override the pager instead or using a library as:
https://github.com/antonyt/InfiniteViewPager
Link to Reference:
ViewPager as a circular queue / wrapping

Related

Video is not getting paused in ViewPager

I m using viewpager and its adapter i m displaying image and video as per condition.
I don't have fragment because i m using PagerAdapter.
Code:
pager.setOnPageChangeListener(pageChangeListener);
pager.post(new Runnable() {
#Override
public void run() {
pageChangeListener.onPageSelected(pager.getCurrentItem());
}
});
}
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
View view = mediaFullScreenImageAdapter.getActiveView(pager);
if (selectedPhotosByDate.get(position).getMessagetype().equalsIgnoreCase("VIDEO")) {
CustomVideoPlayer video_player = (CustomVideoPlayer) view.findViewById(R.id.video_player);
if (video_player.isPlaying()) {
Log.v("THISCALLEDD", "Y" + " : " + position);
video_player.pause();
}
}
}
};
#Nullable
public View getActiveView(final ViewPager viewPager) {
final PagerAdapter adapter = viewPager.getAdapter();
if (null == adapter || adapter.getCount() == 0 || viewPager.getChildCount() == 0) {
return null;
}
int position;
final int currentPosition = viewPager.getCurrentItem();
for (int i = 0; i < viewPager.getChildCount(); i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) child.getLayoutParams();
if (layoutParams.isDecor) {
continue;
}
final Field positionField;
try {
positionField = ViewPager.LayoutParams.class.getDeclaredField("position");
positionField.setAccessible(true);
position = positionField.getInt(layoutParams);
} catch (NoSuchFieldException e) {
break;
} catch (IllegalAccessException e) {
break;
}
if (position == currentPosition) {
return child;
}
}
return null;
}
Update:
selectedPhotosByDate = appDatabase.chatMessagesDao().getMediaByGroupId(topicid, "Y");
if (selectedPhotosByDate.size() > 0 && selectedPhotosByDate != null) {
mediaFullScreenImageAdapter = new MediaFullScreenImageAdapter(MediaFullScreenSlideActivity.this, selectedPhotosByDate);
pager.setAdapter(mediaFullScreenImageAdapter);
for (int i = 0; i < selectedPhotosByDate.size(); i++) {
if (messageid == selectedPhotosByDate.get(i).getMessageId()) {
position = i;
break;
}
}
pager.setCurrentItem(position);
pager.setOffscreenPageLimit(selectedPhotosByDate.size());
}
I am able to get logcat value . But my video doesn't get pause.
If my video is playing and user swipe for other item playing video must be paused.
Advanced help would be appreciated!
Based on the documentation here, onPageSelected is called when a new page is selected. That means, the active view that you are trying to get using the currentItem from the ViewPager will return you the current selected item rather than the previously selected item. So your reference to video_player is also wrong and hence it is not working.
A simple way to do this is to have a variable currentPosition. Update it in onPageSelected but before updating, get its view and pause the video. This way whenever you access it, you will first get the previous index and then you will update it to the current index for the next time.
As per my understanding ,you want to pause previous video when user swipe in viewpager .
#Override
public void onPageSelected(int position) {
View view = mediaFullScreenImageAdapter.getActiveView(pager);
if (selectedPhotosByDate.get(position).getMessagetype().equalsIgnoreCase("VIDEO")) {
CustomVideoPlayer video_player = (CustomVideoPlayer) view.findViewById(R.id.video_player);
if (video_player.isPlaying()) {
Log.v("THISCALLEDD", "Y" + " : " + position);
video_player.pause();
}
}
}
you are getting view object of current active position ,but you want to pause video of (position - 1 ),you need to have view object of previous position .
Finally resolved the issue.
I moved this code
View view = mediaFullScreenImageAdapter.getActiveView(pager);
CustomVideoPlayer video_player = (CustomVideoPlayer) view.findViewById(R.id.video_player);
video_player.pause();
to onPageScrolled() method instead of onPageSelected() method.
This worked for me with a Youtube video playing as an embedded iFrame in a WebView:
viewPager.addOnPageChangeListener(object : SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
// NOTE: this workaround pauses any playing Youtube video in the WebView, if the video screen is being switched out.
// This works by getting the ViewPager#focusedChild, which will be the WebView if that screen is currently in focus,
// before the next selected ViewPager screen gets switched-to/loaded.
viewPager.focusedChild?.findViewById<WebView>(R.id.video_view)?.onPause()
// NOTE: we do a postDelay below, to ensure the WebView gets put back into its resume state, if it being switched to.
// This is delayed, so that this happens after the ViewPager screen with the WebView, has time to load it into place.
postDelayed({ viewPager.focusedChild?.findViewById<WebView>(R.id.video_view)?.onResume() }, 200)
}
})

How to get position of first and last position of viewpager?

I want to hide left arrow when the first position of a ViewPager and hide right arrow when the last position of a ViewPager. And then , I also want to show current page number with TextView like (5/30). 5 is current page number and 30 is total page number. Thank You Sir.
Here is my code;
mPager.beginFakeDrag();
leftNav = (ImageButton) findViewById(R.id.left_nav);
rightNav = (ImageButton) findViewById(R.id.right_nav);
txt_count = (ImageButton) findViewById(R.id.txt);
int tab = mPager.getCurrentItem();
if (tab == 0){
leftNav.setVisibility(View.GONE); // hide all position :(
}
leftNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tab = mPager.getCurrentItem();
if (tab > 0) {
tab--;
mPager.setCurrentItem(tab);
} else if (tab == 0) {
mPager.setCurrentItem(tab);
}
}
});
rightNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tab = mPager.getCurrentItem();
tab++;
mPager.setCurrentItem(tab);
}
});
You can use :
viewPager.getCurrentItem()
ViewPager.getAdapter().getCount() The getAdapter() method returns the object that supplies the pages for the ViewPager.
Add onPageChangeListener as shown below
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == (mPager.getAdapter().getCount() - 1)) {
rightNav.setVisibility(View.GONE);
} else {
rightNav.setVisibility(View.VISIBLE);
}
if (position == 0) {
leftNav.setVisibility(View.GONE);
} else {
leftNav.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Your Click listener for left & right arrow buttons
leftNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mPager.getAdapter() != null && mPager.getAdapter().getCount() != null && mPager.getCurrentItem() != 0) {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
});
rightNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mPager.getAdapter() != null && mPager.getAdapter().getCount() != null && mPager.getCurrentItem() != (mPager.getAdapter().getCount() - 1)) {
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
}
}
});
To get all page count in ViewPager, use getAdapter method of the viewPager.getAdapter()
viewPager.getAdapter().getCount()
To find out current page of ViewPager use ViewPager.getCuurentItem()
viewPager.getCurrentItem()
Use OnPageChangeListener
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
if(position == 0)
{
// hide left nav
}
else if(position == mPager.getAdapter().getCount() - 1) // is last position
{
// hide right nav
}
else
{
// show all nav
}
}
}
Reference
https://developer.android.com/reference/android/support/v4/view/ViewPager.html

MainActivity Get Position Of Item From PagerAdapter [duplicate]

I want to know the current page position of the ViewPager. I create an adapter and set this adapter to the ViewPager. Now I want to know the current page number or position of the current view, because I want to start some extra events on that particular page.
I used viewPager.setCurrentItem(1); for setting the first item.
Is there a similar method for getting the current page?
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;
}
}
There is a method object_of_ViewPager.getCurrentItem() which returns the position of currently Viewed page of view pager
If you only want the position, vp.getCurrentItem() will give it to you, no need to apply the onPageChangeListener() for that purpose alone.
You will figure out that setOnPageChangeListener is deprecated, use addOnPageChangeListener, as below:
ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position == 1){ // if you want the second page, for example
//Your code here
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
For this problem Onpagechange listener is the best one But it will also have one small mistake that is it will not detect the starting time time of 0th position Once you will change the page it will starts to detect the Page selected position...For this problem I fount the easiest solution
1.You have to maintain the selected position value then use it....
2. Case 1: At the starting of the position is always Zero....
Case 2: Suppose if you set the current item means you will set that value into maintain position
3.Then do your action with the use of that maintain in your activity...
Public int maintain=0;
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
//Toast.makeText(MyActivity.this, i+" Is Selected "+data.size(), Toast.LENGTH_SHORT).show();
}
#Override
public void onPageSelected( int i) {
// here you will get the position of selected page
maintain = i;
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
updateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, i+" Is Selected "+data.size(), Toast.LENGTH_SHORT).show();
data.set(maintain, "Replaced "+maintain);
myViewPager.getAdapter().notifyDataSetChanged();
}
});
getCurrentItem(), doesn't actually give the right position for the first and the last page I fixed it adding this code:
public void CalcPostion() {
current = viewPager.getCurrentItem();
if ((last == current) && (current != 1) && (current != 0)) {
current = current + 1;
viewPager.setCurrentItem(current);
}
if ((last == 1) && (current == 1)) {
last = 0;
current = 0;
}
display();
last = current;
}
The setOnPageChangeListener() method is deprecated. Use
addOnPageChangeListener(OnPageChangeListener) instead.
You can use OnPageChangeListener and getting the position inside onPageSelected() method, this is an example:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d(TAG, "my position is : " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Or just use getCurrentItem() to get the real position:
viewPager.getCurrentItem();
There is no any method getCurrentItem() in viewpager.i already checked the API

How can I make my arrows invisible by setCurrentItem method of Viewpager?

In Oncreate of my MainActivity I add this code:
mDateAreaSlider.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// Hide right arrow if reach last position
if (arg0 == adapter.DateList.length - 1) {
mButtonNext.setVisibility(View.INVISIBLE);
mButtonBack.setVisibility(View.VISIBLE);
}
// Hide left arrow if reach first position
else if (arg0 == 0) {
mButtonBack.setVisibility(View.INVISIBLE);
mButtonNext.setVisibility(View.VISIBLE);
}
// Else show both arrows
else {
mButtonBack.setVisibility(View.VISIBLE);
mButtonNext.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
ifSingding = true;
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
and on the button click I add this code:
mDateAreaSlider.setCurrentItem(0);
but the problem is it can slide to the page I selected but does not make my arrows invisible.
NOTE: The 2 arrows are ImageViews in main layout,not inflated layout.So it is nothing to do with adapter.
Replace your original code with this:
final ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == adapter.DateList.length - 1) {
mButtonNext.setVisibility(View.INVISIBLE);
mButtonBack.setVisibility(View.VISIBLE);
}
// Hide left arrow if reach first position
else if (position == 0) {
mButtonBack.setVisibility(View.INVISIBLE);
mButtonNext.setVisibility(View.VISIBLE);
}
// Else show both arrows
else {
mButtonBack.setVisibility(View.VISIBLE);
mButtonNext.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
mDateAreaSlider.addOnPageChangeListener(onPageChangeListener);
Execute this code on your button click
mDateAreaSlider.setCurrentItem(0);
mDateAreaSlider.post(new Runnable() {
#Override
public void run() {
onPageChangeListener.onPageSelected(0);
}
});

stoping the SwipeMenuLIstView to Swipe

i am using Swipe menu list View from the Githu
https://github.com/baoyongzhang/SwipeMenuListView
According to my project requirement i need to stop some list View to Swipe
for example i want to stop the list item on the postion 5
how i would do that
mListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
#Override
public void onSwipeStart(int position) {
if (positon == 5) {
Toast.makeText(getApplicationContext(), "you are not Allow to Swipe", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSwipeEnd(int position) {
}
});
You can create a private instance of the listener and than set it to the mListView if a condition is met and if you want to not allow the swiping to be active you can simply set the onSwipeListener to null like this:
private SwipeMenuListView.OnSwipeListener swipeListener = new SwipeMenuListView.OnSwipeListener() {
#Override
public void onSwipeStart(int i) {
}
#Override
public void onSwipeEnd(int i) {
}
});
if (condtion) {
Toast.makeText(getApplicationContext(), "you are not Allow to Swipe", Toast.LENGTH_SHORT).show();
//disable swiping
mListView.setOnSwipeListener(null);
}else{
//allow swiping
mListView.setOnSwipeListener(swipeListener);
}
you can use BaseSwipListAdapter and change condition according your requirments.
#Override
public boolean getSwipEnableByPosition(int position) {
if(position==5){
return false;
}
return true;
}

Categories

Resources