Android - ViewPager内的片段Animate RecyclerView项目

时间:2015-08-31 03:13:39

标签: android android-fragments android-viewpager android-animation

我正在使用ViewPager Fragments。每个片段都有RecyclerView GridLayoutManager。在我的RecyclerView适配器中,我在onBindViewHolder上设置了动画。

问题:

当ViewPager一次加载两个片段时,即使视图不可见,第二个片段的动画也会完成

预期产出:

当有人在viewPager上滑动时,所有RecyclerView项目都应该设置动画。

RecyclerView适配器

public void onBindViewHolder(ViewHolder viewHolder, final int position) {

    viewHolder.getServiceImageView().setImageResource(mServices.get(position).getImageResource());
    viewHolder.getServiceNameView().setText(mServices.get(position).getServiceName());
    viewHolder.getPricePerHourView().setText(String.valueOf(mServices.get(position).getPricePerHour()));
    setAnimation(viewHolder.serviceItemContainer, position);
}

private void setAnimation(View viewToAnimate, int position)
{
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition)
    {
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
        viewToAnimate.startAnimation(animation);
        lastPosition = position;
    }
}

片段代码

public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_cleaning, container, false);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), SPAN_COUNT));
    mServicesAdapter = new RecyclerViewAdapter(getContext(), data);
    mRecyclerView.setAdapter(mServicesAdapter);
    return rootView;
}

ViewPager适配器

private class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                fragment = new Fragment1();
            case 1:
                return new Fragment2();
            case 2:
                return new Fragment3();
            default:
                return new Fragment4();
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            case 3:
                return getString(R.string.title_section4).toUpperCase(l);
        }
        return null;
    }

有谁能建议我怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个

  1. 在要设置动画的片段的活动中实现自己的onResumeFragment()
  2. 在onResumeFragment()上调用adapter.notifyDataSetChanged();开始制作动画