使用简介滑块滑动时动画错误

时间:2018-05-04 19:51:17

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

我有一个viewpager看起来像介绍滑块,我希望在滑动滑块时启动uptodown和downtoup动画:

我的寻呼机适配器代码是:

public class mpageradapter extends FragmentPagerAdapter {
private final int[] Layouts;
public mpageradapter(FragmentManager fm, int [] Layouts) {
    super(fm);
    this.Layouts=Layouts;
}

@Override
public Fragment getItem(int position) {
    switch (position){
        case 0:return new first_slide();
        case 1:return new second_slide();
        case 2:return new third_slide();
        case 3:return new final_slide();
        default:return null;
    }
}

@Override
public int getCount() {
    return Layouts.length;
}

}

我的片段滑块代码是:

public class first_slide extends Fragment {
RelativeLayout t1,t2;
Animation uptodown,downtoup;

@Override
public void onStart() {
    super.onStart();
    uptodown = AnimationUtils.loadAnimation(getContext(), R.anim.uptodown);
    downtoup = AnimationUtils.loadAnimation(getContext(), R.anim.downtoup);
    t1.startAnimation(uptodown);
    t2.startAnimation(downtoup);
    Log.i("first", "onStart: first");
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  View view=inflater.inflate(R.layout.first_slide,container,false);
    t1 = (RelativeLayout) view.findViewById(R.id.t1);
    t2 = (RelativeLayout)view. findViewById(R.id.t2);
  return view;
}

}

错误的是滑动第一个和第三个是动画而第二个和第三个不是。 我认为是因为viewpager首先创建了前两个,在从第二个到第三个滑动之后,viewpager创建了第三个和第四个 当我浏览介绍滑块时,如何为每个片段提供动画和动画片

1 个答案:

答案 0 :(得分:1)

我还在viewpager的介绍屏幕中遇到了动画问题。 如果我正确理解了你的问题,我的回答可以帮助你或提示...... 我已经使用setUserVisibleHint()检查片段是否对用户可见isLoaded boolean flag来检查片段是否已加载。

private boolean isVisibleToUser = false;
private boolean isLoaded = false;
 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    Log.e("isVisibleToUser  " + isVisibleToUser + " isLoaded : " + isLoaded);

    this.isVisibleToUser = isVisibleToUser;

    if (isVisibleToUser && isLoaded) {
        playAnimation();
    }
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.onboarding_screen1, container, false);
    handler = new Handler();

    if (isVisibleToUser && (!isLoaded)) {
                init();
                playAnimation();
                isLoaded = true;
        }
    }

    return view;
}