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
Related
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)
}
})
I found a library on github that has CarouselPicker com.github.Vatican-Cameos:CarouselPicker:v1.0 i added this in the dependencies and compile also in repositories maven { url 'https://jitpack.io'}
I have successfully make a CarouselPicker this is the JAVA CODE
carouselPicker = (CarouselPicker)findViewById(R.id.carouselPicker);
List<CarouselPicker.PickerItem> itemsImage = new ArrayList<>();
itemsImage.add(new CarouselPicker.DrawableItem(R.drawable.abc));
itemsImage.add(new CarouselPicker.DrawableItem(R.drawable.123));
itemsImage.add(new CarouselPicker.DrawableItem(R.drawable.colors));
itemsImage.add(new CarouselPicker.DrawableItem(R.drawable.shapes));
CarouselPicker.CarouselViewAdapter imageAdapter = new CarouselPicker.CarouselViewAdapter(this, itemsImage,0);
carouselPicker.setAdapter(imageAdapter);
And by having a LinearLayout this is the XML code
<in.goodiebag.carouselpicker.CarouselPicker
android:id="#+id/carouselPicker"
android:layout_marginTop="50dp"
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:items_visible="three"
/>
I cant find on google on what if the 1st item in the carousel picker selected like a OnClickListenerto change the intent
I found a library you used on this link
You must use addOnPageChangeListener like this:
carouselPicker.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//position of the selected item
if(position == 0){
startActivity(new Intent(thisActivity.this, anotherActivity1.class));
}
else if(position == 1){
startActivity(new Intent(thisActivity.this, anotherActivity2.class));
}
// Same conditions for another cases.
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
So, your onClickListener that you want to handle the click event, is onPageSelected method.
I am using ViewPager which contains Fragment which contains RecyclerView. There I am trying to auto-refresh only current(which is visible) page view every 10 seconds. But the problem is after 10 seconds handler.postDelayed() is updating view of the next page view (not which is visible). I know it's because pager loads 1 extra page and this is causing holder to update with that next view and handler.postDelayed() is updating that next view in holder.
How to solve this problem.
here is my autorefresh method, I am calling it from onBindViewHolder();
private void startAutoRefresh(final ViewHolder holder, final String exchange,
final int currentPosition, final int timer){
new FetchData(holder, exchange, firstTimeLoadPosition).execute(
Configuration.exchangesAPI.get(exchange));
if (MainActivity.pagerPosition == currentPosition) {
counterView.setText(timer + "");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (timer > 0) {
counterView.setText(timer + "");
startAutoRefresh(holder, exchange, currentPosition, timer - 1);
} else {
Log.wtf("Reloading", currentPosition+"");
new FetchData(holder, exchange, currentPosition).execute(
Configuration.exchangesAPI.get(exchange));
startAutoRefresh(holder, exchange, MainActivity.pagerPosition, counter);
}
}
}, 1000);
}
}
use an interface and pass that interface as a parameter of the adapter... in the interface interface GetPositionFromMainActivity extends Parcelable{int getPosition();} and in MainActivity after setting adapter of view paper GetPositionFromMainActivity getpos = new GetPositionFromMainActivity { #override getpos{ return viewpager.getPosition()} and in recycler adapter if(interface.getPos == currentPosition) instead of a static variable.. I mean just use an interface instead of a static variable...
pass the interface to the adapter of viewpager ..and in the getItem of viewPagerAdapter pass the interface as putParcelable as bundle arguments.. get the arguments the fragment and pass the imterface to the recycler adapter...
You can use onPageSelected method of ViewPager.OnPageChangeListenr for this. For example,
ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
// It returns the position of currently visible page.
// Write your code here, according to your slide position using switch or if else.
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
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
I have an application with one Activity (ActivityMain) and some fragments. A NavigationDrawer controls the switch of the fragments. In some fragments the user has the opportunity to switch to another fragment without opening the NavigationDrawer (for example with a button click).
Everything works well, if I use the NavigationDrawer to switch between fragments, but if I use a control (eg. button) within a fragment to switch to another fragment, I cannot set the selectedItem property of the NavigationDraver's (actually a ListView in the ND) selectedItem property.
The NavigationDrawer's selectedItem property is stored with sharedPreferences, and restored in the onDrawerOpened method in the NavigationDrawer fragment.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
I've tried to put the selection index within the onClick event of the View to STATE_SELECTED_POSITION value, as follows, but it doesn't worked. I've also cannot get the value from the sharedPreferences in the other Fragment.
public void navigationRowClick(View view) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
switch(view.getId()) {
case R.id.tr_conv:
sp.edit().putInt(STATE_SELECTED_POSITION, 1);
((MainActivity)getActivity()).changeFrame(1);
((MainActivity)getActivity()).restoreActionBar();
break;
case R.id.trCalc:
sp.edit().putInt(STATE_SELECTED_POSITION, 2);
((MainActivity)getActivity()).changeFrame(2);
((MainActivity)getActivity()).restoreActionBar();
break;
case R.id.trCalo:
Integer i = sp.getInt(STATE_SELECTED_POSITION, 100); // get value test
String s = i.toString();
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
break;
}
}
My question is, how should I set the selectedItem of the NavigationDrawer from another fragment? Do You have a best practice to this task?
Thanks is advance for the suggestions.
in the onClick event for the button that switches the fragment:
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity) getActivity()).changePosition(1);
sp.edit().putInt(STATE_SELECTED_POSITION, 1).**commit()**;
}
});
//in MainActivity.java
private void changePosition(int position)
{
list.setItemChecked(position, true);
}
this works if you have set the android:choiceMode="singleChoice" attribute to the list.
Another way of doing things is to do it in the adapter of the listview:
.....
{
private int mSelectedItem = 0;
public View getView(int position, View convertView, ViewGroup parent)
{
if(position == mSelectedItem)
{
}
else
{
}
}
public void setSelectedItem(int position)
{
mSelectedItem = position;
}
}
//in MainActivity.java
private void changePosition(int position)
{
adapter.setSelectedItem(position);
adapter.notifyDataSetChanged();
}
Also make sure to commit the changes to the SharedPreferences:
sp.edit().putInt(STATE_SELECTED_POSITION, 1).**commit()**;
maybe you are doing it in some other place, but I don't see it in the snippets you have shown.