首页 > 解决方案 > 如何使用片段转换为视图或按钮设置动画?

问题描述

我创建了一个带有 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;
    }

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

标签: javaandroidandroid-fragments

解决方案


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

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

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

推荐阅读