简体   繁体   English

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

[英]How to animate a view or button with fragment transition?

I created a ViewPager with 5 fragments.我用 5 个片段创建了一个 ViewPager。 Each fragment has a button.每个片段都有一个按钮。 I want to rotate that button with fragment transition.我想用片段过渡旋转那个按钮。 What happens that all the five buttons rotate when I start the activity, so I only see the rotation of the button of the first fragment.当我开始活动时,所有五个按钮都会旋转,所以我只看到第一个片段的按钮旋转会发生什么情况。 This is the code I used for each fragment:这是我用于每个片段的代码:

        @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;
    }

I want the animation of each button to start only when I get to the fragment that contains it.我希望每个按钮的动画只有在我到达包含它的片段时才开始。 Any help is appreciated.任何帮助表示赞赏。 Thank you all.谢谢你们。

That's because all 5 fragments get created almost the same time, so you shouldn't start the animation inside the onCreateView instead start it when the fragment is visible to the user.这是因为所有 5 个片段几乎是同时创建的,因此您不应在onCreateView内启动动画,而是在用户可见片段时启动它。

You can achieve this by calling the onResume method inside each fragment, but you must call BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT behavior in the constructor of the ViewPager adapter.您可以通过在每个片段内调用onResume方法来实现这一点,但您必须在 ViewPager 适配器的构造函数中调用BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT行为。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM