After viewpager adapter notifyDataSetChanged,pagetransformer not work - android

I use ViewPager and PageAdapter to show my data and the ViewPager has its PageTransformer, it works well and now I need to update data and UI when sliding to a new item but the problem is when I slide to the new item and call `adapter.notifyDataSetChanged(), my data and UI do updated but my PageTransformer do not work.
Here is my code:
mAdapter = new DynamicsCardAdapter(getContext(), mList);
mViewPager.setPageTransformer(true, new ZoomOutPageTransformer2());
mViewPager.setPageMargin(-(int) (width * 0.30));
mViewPager.setAdapter(mAdapter);
Adapter:
public class DynamicsCardAdapter extends PagerAdapter {
private Context mContext;
private List<ChildDynamicsInfo> mList;
private int mPosition = -1;
private int mChildCount = 0;
public DynamicsCardAdapter(Context context, List<ChildDynamicsInfo> list) {
mContext = context;
mList = list;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup viewGroup, int position) {
View convertView = LayoutInflater.from(mContext).inflate(R.layout.item_parent_dynamics_card, viewGroup, false);
textName = (TextView) convertView.findViewById(R.id.student_name);
textName.setText(mList.get(position).name);
viewGroup.addView(convertView);
return convertView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#Override
public void notifyDataSetChanged() {
mChildCount = getCount();
super.notifyDataSetChanged();
}
#Override
public int getItemPosition(#NonNull Object object) {
//return POSITION_NONE;
if ( mChildCount > 0) {
mChildCount --;
return POSITION_NONE;
}
return super.getItemPosition(object);
}
}
PageTransformer:
public class ZoomOutPageTransformer2 implements ViewPager.PageTransformer {
private static final float MAX_ROTATE = 30.0f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
float currentRotate = position * MAX_ROTATE;
if (position < 0) {
view.setPivotX(pageWidth / 2);
view.setPivotY(view.getHeight());
view.setRotation(currentRotate);
} else if (position <= 1) {
view.setPivotX(pageWidth / 2);
view.setPivotY(view.getHeight());
view.setRotation(currentRotate);
} else if (position == 0) {
view.setRotation(0);
}
}
}
Update data:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mList.get(position).isRead = true;
mAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I just want to update my UI when sliding to a new item and make sure that my PageTransformer work well, I used to try :
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(position);
but because I update UI on onPageSelected() so it will cause StackOverFlow.

Related

ViewPager2 fragment click event

I'm trying to use viewpager2 in fragment and make each pages clickable.
But all solutions are not working for me.
I tried to make ListPageAdapter to extend RecyclerView.ViewHolder and custom viewHolder by using onCreateViewHolder and onBindViewHolder like recyclerView but it already extended FragmentStateAdapter for making fragment.
How can i make it clickable?
Here is my code
ListPageAdapter.java
public class ListPageAdapter extends FragmentStateAdapter {
public int mCount;
private LayoutInflater mInflate;
private OnListItemClickListener listener;
public ListPageAdapter(FragmentActivity fa, int count) {
super(fa);
mCount = count;
}
#NonNull
#Override
public Fragment createFragment(int position) {
int index = getRealPosition(position);
if(index==0) return new Swipe1();
else if(index==1) return new Swipe2();
else if(index==2) return new Swipe3();
else if(index==3) return new Swipe4();
else return new Swipe5();
}
#Override
public int getItemCount() {
return 2000;
}
public int getRealPosition(int position) { return position % mCount; }
}
TextSearch.java
public class TextSearch extends AppCompatActivity {
private Button submitBtn;
private CircleIndicator3 mIndicator;
private ViewPager2 mPager;
private FragmentStateAdapter pagerAdapter;
private int num_page = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_search);
submitBtn = findViewById(R.id.submitBtn);
//ViewPager2
mPager = findViewById(R.id.viewpager);
//Adapter
pagerAdapter = new ListPageAdapter(this, num_page);
//Indicator
mIndicator = findViewById(R.id.indicator);
//ViewPager Setting
mPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
mPager.setCurrentItem(1000);
mPager.setOffscreenPageLimit(3);
mPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
if (positionOffsetPixels == 0) {
mPager.setCurrentItem(position);
}
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
mIndicator.animatePageSelected(position % num_page);
}
});
final float pageMargin = getResources().getDimensionPixelOffset(R.dimen.pageMargin);
final float pageOffset = getResources().getDimensionPixelOffset(R.dimen.offset);
mPager.setPageTransformer(new ViewPager2.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
float myOffset = position * -(2 * pageOffset + pageMargin);
if (mPager.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) {
if (ViewCompat.getLayoutDirection(mPager) == ViewCompat.LAYOUT_DIRECTION_RTL) {
page.setTranslationX(-myOffset);
} else {
page.setTranslationX(myOffset);
}
} else {
page.setTranslationY(myOffset);
}
}
});
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setAdapter(pagerAdapter);
mIndicator.setViewPager(mPager);
mIndicator.createIndicators(num_page, 0);
String sendText = textLine.getText().toString();
Log.d("calling", sendText);
FileUploadUtils.sendText(sendText);
}
});
}
}
You can use the same approach as for a common fragments. In Fragment(page of a pager) Override onAttach method and implement it like this.
#Override
public void onAttach(#NotNull Context context) {
super.onAttach(context);
try {
pageClickListener = ((PageClickListener) context);
} catch (Exception e) {
Log.e("SwipeFragment", "Root activity must implement PageClickListener");
}
}
And a root activity have to implement your listener.
public class MainActivity implements PageClickListener

Implemnetation of Inner view pager

I have implemented one view pager inside other. Requirement was to have tabs on parent view pager and show its item on child view pager. Example, parent view pager has two tabs (episode, videos) and we have number of episodes and vidoes(child view pager) which need to be displayed in respective tabs. Problem is when I swipe from the edges of the screen, it changes the tab even though current tab has more item to load. But it works fine when I swipe from center of the screen and shows next episode when i am on episode tab.
Here is a code :
public class ParentPagerAdapter extends FragmentStatePagerAdapter {
private List<String> tabList;
private boolean isPilot;
private ArrayList<?extends IVideoModel> videoList;
private ArrayList<?extends IEpisodeAndVideoModel> episodeList;
public ParentPagerAdapter(FragmentManager fm, List<String> tabList,
ArrayList<?extends IEpisodeModel> episodeList, ArrayList<?extends IVideoModel>
videoList) {
super(fm);
this.episodeList = episodeList;
this.videoList = videoList;
this.tabList = tabList;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
Bundle bundle = new Bundle();
if(tabList.get(position).contains(VIDEOS_TAB_TITLE)){
fragment = new VideoTabFragment();
return fragment;
}else if(tabList.get(position).contains(EPISODES_TAB_TITLE)){
fragment = new EpisodeTabFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return tabList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabList.get(position);
}
#Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
}
Child view Pager 1:
public class ProjectVideoPagerAdapter extends PagerAdapter {
public final String TAG = ProjectVideoPagerAdapter.class.getCanonicalName();
private Context mContext;
private LayoutInflater mLayoutInflator;
private RowProjectLandingPagerItemBinding itemBinding;
private List<? extends IVideoModel> projectVideoList;
public ProjectVideoPagerAdapter(Context context, List<? extends IVideoModel> projectVideoList) {
mContext = context;
this.projectVideoList = projectVideoList;
mLayoutInflator = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
debugLog("Entering instantiateItem with position = " + position);
itemBinding =
DataBindingUtil.inflate(mLayoutInflator, R.layout.row_project_landing_pager_item, null,
false);
if (projectVideoList == null) return null;
container.addView(itemBinding.getRoot());
debugLog("Exiting instantiateItem()");
return itemBinding.getRoot();
}
#Override
public int getCount() {
if (projectVideoList != null && !projectVideoList.isEmpty()) return projectVideoList.size();
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager)container).removeView((View)object);
//super.destroyItem(container, position, object);
}
}
Child view pager 2:
public class ProjectVideoPagerAdapter extends PagerAdapter {
public final String TAG = ProjectVideoPagerAdapter.class.getCanonicalName();
private Context mContext;
private LayoutInflater mLayoutInflator;
private RowProjectLandingPagerItemBinding itemBinding;
private List<? extends IEpisodeModel> projectEpisodeList;
public ProjectVideoPagerAdapter(Context context, List<? extends IEpisodeModel> projectList) {
mContext = context;
this.projectEpisodeList = projectList;
mLayoutInflator = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
debugLog("Entering instantiateItem with position = " + position);
itemBinding =
DataBindingUtil.inflate(mLayoutInflator, R.layout.row_project_landing_pager_item, null,
false);
if (projectEpisodeList == null) return null;
container.addView(itemBinding.getRoot());
debugLog("Exiting instantiateItem()");
return itemBinding.getRoot();
}
#Override
public int getCount() {
if (projectEpisodeList != null && !projectEpisodeList.isEmpty()) return projectEpisodeList.size();
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager)container).removeView((View)object);
//super.destroyItem(container, position, object);
}
}
With inner view pager, you should use "childfragmentmanager" instead of "fragmentmanager". It works fine.

ViewPager content not able to reset after page scrolled

I having a view pager, which having a textview and initially set to View.INVISIBLE and when the page comes to focus it fades in.
But when i am scrolled to next page and taking previous view the Text View is in Visible state but supposed to be in INVISIBLE state.
I tried with setting the textview to invisble through storing the previous index. But its not resetting the textview.
index = indexCalculator(index);
Log.d("HeadIndex",""+index);
CustomViewPagerAdapter customViewPagerAdapter = (CustomViewPagerAdapter) viewPagerAdapter;
ImageSliderFragment fragment = customViewPagerAdapter.getFragment(index);
fragment.getView().findViewById(R.id.head_data).setVisibility(View.INVISIBLE);
Canyone help me how to set the view to INVISIBLE.
UPDATE Code:
private class CustomViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, ImageSliderFragment> mPageReferenceMap = new HashMap<>();
public CustomViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ImageSliderFragment imageSliderFragment = new ImageSliderFragment();
Bundle args = new Bundle();
args.putInt(AppConstants.BUNDLE_KEY_FOR_FRAGMENT_POSITION,position);
imageSliderFragment.setArguments(args);
mPageReferenceMap.put(Integer.valueOf(position),imageSliderFragment);
return imageSliderFragment;
}
#Override
public int getCount() {
return AppConstants.NUM_PAGES;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;//super.getItemPosition(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
public ImageSliderFragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
}
PageChangeListener code:
public class CircularViewPagerHandler implements ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
private int mCurrentPosition;
private int mScrollState;
///For determining swipe direction
private static final float thresholdOffset = 0.5f;
private boolean scrollStarted, checkDirection;
private HeadDataListener headDataListener;
public CircularViewPagerHandler(final ViewPager viewPager,HeadDataListener listener) {
mViewPager = viewPager;
headDataListener = listener;
}
#Override
public void onPageSelected(final int position) {
mCurrentPosition = position;
headDataListener.showHead(position);
Log.d("OnPageSelected",""+position);
}
#Override
public void onPageScrollStateChanged(final int state) {
handleScrollState(state);
mScrollState = state;
if (!scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
scrollStarted = true;
checkDirection = true;
} else {
scrollStarted = false;
}
}
private void handleScrollState(final int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
setNextItemIfNeeded();
}
}
private void setNextItemIfNeeded() {
if (!isScrollStateSettling()) {
handleSetNextItem();
}
}
private boolean isScrollStateSettling() {
return mScrollState == ViewPager.SCROLL_STATE_SETTLING;
}
private void handleSetNextItem() {
final int lastPosition = mViewPager.getAdapter().getCount() - 1;
if(mCurrentPosition == 0) {
mViewPager.setCurrentItem(lastPosition, false);
} else if(mCurrentPosition == lastPosition) {
mViewPager.setCurrentItem(0, false);
}
}
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
if (checkDirection) {
if (thresholdOffset > positionOffset) {
AppConstants.SWIPE_DIRECTION = 1;
} else {
AppConstants.SWIPE_DIRECTION = 2;
}
checkDirection = false;
}
}
}
I have implemented a callback to my class
Set the visibility of the view at the XML
android:visibility="gone"
then change the visibity of the view at onPageSelected() method at the CustomPagerAdapter

How can i getCurrentView by position in a ViewPager?

I need getCurrentView by position in a ViewPager
This my ViewPagerAdapter
public class TutorialViewPagerAdapter extends ViewPagerAdapter {
private LayoutInflater mInflater;
private View view;
private List<Integer> views;
public TutorialViewPagerAdapter(Activity act, List<Integer> views) {
super(act, null);
this.views = views;
this.mInflater = LayoutInflater.from(this.activity);
}
#Override
public void destroyItem(View container, int arg1, Object view) {
((ViewPager) container).removeView((View) view);
}
#Override
public int getCount() {
return views.size();
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
int viewId = (Integer) views.get(position);
this.view = mInflater.inflate(viewId, null);
((ViewPager) collection).addView(view);
return view;
}
}
And this is my activity
public class Tutorial extends FragmentActivity implements
ViewPager.OnPageChangeListener {
private List<Integer> views;
private TutorialViewPagerAdapter viewPagerAdapter;
private ViewPager viewPager;
private CirclePageIndicator circlePageIndicator;
private int currentViewId;
private View currentView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
init();
}
private void init() {
views = new ArrayList<Integer>();
views.add(R.layout.tutorial_step_one);
views.add(R.layout.tutorial_step_two);
views.add(R.layout.tutorial_step_three);
views.add(R.layout.tutorial_step_four);
views.add(R.layout.tutorial_step_five);
viewPagerAdapter = new TutorialViewPagerAdapter(this, views);
viewPager = (ViewPager) findViewById(R.id.steps_view_pager);
circlePageIndicator = (CirclePageIndicator) findViewById(R.id.steps_indicator);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setCurrentItem(0, false);
circlePageIndicator.setViewPager(viewPager);
circlePageIndicator.setCentered(true);
circlePageIndicator.setPadding(20, 20, 20, 20);
circlePageIndicator.notifyDataSetChanged();
circlePageIndicator.setCurrentItem(0);
viewPager.setOnPageChangeListener(this);
}
#Override
public void onPageScrollStateChanged(int state) {
int currentPosition = viewPager.getCurrentItem();
circlePageIndicator.setCurrentItem(currentPosition);
enableStep(currentPosition);
}
private void enableStep(int currentPosition) {
/*viewPagerAdapter.getItemPosition(object)
currentView = viewPager.getChildAt(viewPager.getRootView());
Log.d("DEBUG", currentView.toString() + " CURRENT VIEW");*/
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
}
You could add all your created views in instantiateItem to an ArrayList<View> and then make a public method for getting a view from the ArrayList with get(position). But be carefully, as soon the Activity is finished the views could be null
Instead of ViewPagerAdapter you can use FragmentPagerAdapter which will have getItem(int position) method by using which you can easily access view.
You can take a look at this post : Android Return back to same fragment after click on goto first fragment in view pager
Hope this help!!
It's moot point. What exactly You need? Current view or view by position. Imho it is different things.
Current view:
currentView = viewPager.getCurrentItem();
Or view by index (you pass wrong parameter - should be int):
currentView = viewPager.getChildAt(currentPosition);

(AndroidTouchGallery) How to start with 2,3,4.. image. How to set position

I`m trying to implement ImageGallery on Android. I use AndroidTouchGallery library. In MainActyvity I have list of images and by clicking on them open AndroidTouchGallery. Everything work, but when open the image gallery starts with the first one.
There need to set the image position, in which to start. In this stage I have a problem. Maybe someone how to make it.
int pos ; //Picture Position
UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(Full_Image_Activity.this, ArrayImgBig);
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);
The code of UrlPageAdapter. I try to set the position in setPrimaryItem, but it still open the first image.
/**
Class wraps URLs to adapter, then it instantiates {#link UrlTouchImageView} objects to paging up through them.
*/
public class UrlPagerAdapter extends BasePagerAdapter {
public UrlPagerAdapter(Context context, List<String> resources)
{
super(context, resources);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
((GalleryViewPager)container).mCurrentView = ((UrlTouchImageView)object).getImageView();
}
#Override
public Object instantiateItem(ViewGroup collection, int position){
final UrlTouchImageView iv = new UrlTouchImageView(mContext);
iv.setUrl(mResources.get(position));
iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
collection.addView(iv, 0);
return iv;
}
}
BasePagerAdapter
/**
Class wraps URLs to adapter, then it instantiates <b>UrlTouchImageView</b> objects to paging up through them.
*/
public class BasePagerAdapter extends PagerAdapter {
protected final List<String> mResources;
protected final Context mContext;
protected int mCurrentPosition = -1;
protected OnItemChangeListener mOnItemChangeListener;
public BasePagerAdapter()
{
mResources = null;
mContext = null;
}
public BasePagerAdapter(Context context, List<String> resources)
{
this.mResources = resources;
this.mContext = context;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (mCurrentPosition == position) return;
GalleryViewPager galleryContainer = ((GalleryViewPager)container);
if (galleryContainer.mCurrentView != null) galleryContainer.mCurrentView.resetScale();
mCurrentPosition = position;
if (mOnItemChangeListener != null) mOnItemChangeListener.onItemChange(mCurrentPosition);
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view){
collection.removeView((View) view);
}
#Override
public int getCount()
{
return mResources.size();
}
#Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
#Override
public void finishUpdate(ViewGroup arg0){
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState(){
return null;
}
#Override
public void startUpdate(ViewGroup arg0) { }
public int getCurrentPosition() { return mCurrentPosition; }
public void setOnItemChangeListener(OnItemChangeListener listener) { mOnItemChangeListener = listener; }
public static interface OnItemChangeListener
{
public void onItemChange(int currentPosition);
}
}
Olso I have some other queston.
*is the "setPrimaryItem" set up the main Item(Image) witch is open first?
*is the "instantiateItem" initialise every item from the array, whitch is shows?
I made it by this:
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);
//set position
mViewPager.setCurrentItem(pos);

Categories

Resources