如何使用片段过渡为视图或按钮设置动画?

时间:2019-12-07 19:55:18

标签: java android android-fragments

我创建了一个包含5个片段的ViewPager。每个片段都有一个按钮。我想旋转带有片段过渡的按钮。当我开始活动时,五个按钮全部旋转会发生什么,所以我只看到第一个片段的按钮的旋转。这是我用于每个片段的代码:

        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.quote_1, container, false);

        quoteOneShareButton = rootView.findViewById(R.id.q_one_share_btn);
        //code to rotate share btn with fragment transition:
        RotateAnimation rotateAnimation1 = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation1.setDuration(1500);
        rotateAnimation1.setInterpolator(new LinearInterpolator());
        quoteOneShareButton.startAnimation(rotateAnimation1);
        //end of rotation code
        return rootView;
    }

我希望每个按钮的动画仅在到达包含它的片段时才开始。任何帮助表示赞赏。谢谢大家。

1 个答案:

答案 0 :(得分:1)

这是因为所有5个片段几乎都是同时创建的,因此您不应在onCreateView内启动动画,而应在用户可见该片段时启动它。

您可以通过在每个片段内调用onResume方法来实现此目的,但是必须在ViewPager适配器的构造函数中调用BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT行为。

@Override
public void onResume(){
    super.onResume();
    // animtion code..
}