我使用ViewPager
andPageAdapter
来显示我的数据,而 ViewPager 有它PageTransformer
,它运行良好,现在我需要在滑动到新项目时更新数据和 UI,但问题是当我滑动到新项目并调用`adapter.notifyDataSetChanged() ,我的数据和 UI 确实更新了,但我的 PageTransformer 不起作用。
这是我的代码:
mAdapter = new DynamicsCardAdapter(getContext(), mList);
mViewPager.setPageTransformer(true, new ZoomOutPageTransformer2());
mViewPager.setPageMargin(-(int) (width * 0.30));
mViewPager.setAdapter(mAdapter);
适配器:</p>
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);
}
}
页面转换器:</p>
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);
}
}
}
更新数据:</p>
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) {
}
});
我只想在滑动到新项目时更新我的 UI 并确保我的 PageTransformer 运行良好,我曾经尝试过:
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(position);
但是因为我更新了 UIonPageSelected()
所以会导致StackOverFlow
.