等待Android动画完成

时间:2013-10-03 01:31:33

标签: android multithreading animation

我想知道是否有人可以帮助我,我一直在寻找有用的帮助,但一无所获。我有四个View元素(Button s),我需要以随机顺序依次为它们设置动画。我已经尝试等待Animation.hasEnded(),这只会冻结整个应用。此外,我尝试等待AnimationListener更改onAnimationEnd()的布尔值,但这也冻结了应用程序。等待的Thread.sleep()SystemClock.sleep()都给出了相同的结果。拜托,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

我是这样做的:

首先,为随机按钮数组创建一个成员:

private Button[] mRandomButtonsOrder;

然后,初始化随机按钮顺序:

List<Button> myButtons = new ArrayList<Button>();

        myButtons.add(btn1); // Add all your buttons to this array.
        myButtons.add(btn2);
        myButtons.add(btn3);
        myButtons.add(btn4);

        mRandomButtonsOrder = new Button[myButtons.size()]; // This is a member of the activity!

        Random random = new Random();
        int index; 

        for (int i = 0; i < myButtons.size(); i++)
        {
            do
            {
                index = random.nextInt() % mRandomButtonsOrder.length;
            } while (mRandomButtonsOrder[index] != null);

            mRandomButtonsOrder[index] = myButtons.get(0);
            myButtons.remove(0);
        }

        initiateAnimationOnButton(0);

现在,这是initateAnimationOnButton方法:

private void initiateAnimationOnButton(final int buttonIndex)
    {
        TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta); // Just a sample using TranslateAnimation
        animation.setDuration(1000);

        if (buttonIndex < mRandomButtonsOrder.length - 1)
        {
            animation.setAnimationListener(new TranslateAnimation.AnimationListener() 
            {

                @Override
                public void onAnimationStart(Animation animation) { }

                @Override
                public void onAnimationRepeat(Animation animation) { }

                @Override
                public void onAnimationEnd(Animation animation) 
                {
                    initiateAnimationOnButton(buttonIndex + 1);                         
                }
            });
        }

        Button btn = mRandomButtonsOrder[buttonIndex];
        btn.startAnimation(animation);
    }

希望这会有所帮助:)