无法在浮动操作按钮上重复动画

时间:2015-08-18 14:54:53

标签: android android-asynctask android-animation floating-action-button

既然我可以为FloatingActionButton制作动画,我还有另一个问题。

当我点击FAB时,FAB的旋转开始并一直持续到AsyncTask完成其工作。

以下是相关代码的部分:

@OnClick(R.id.floating_action_button) //Butterknife feature
    public void refreshAccountInfo(){
        APIHandler api = new APIHandler(databaseHelper, c, getActivity());
        AccountSync accountSync = new AccountSync(api);
        accountSync.execute();
    }

    public class AccountSync extends AsyncTask<Void,Void,Account> {

        APIHandler apiHandler;
        ObjectAnimator animation;

        public AccountSync(APIHandler api){
            apiHandler = api;
        }

        @Override
        protected void onPreExecute(){
            FloatingActionButton button = ButterKnife.findById(getActivity(), R.id.floating_action_button);
            PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, -360);
            animation = ObjectAnimator.ofPropertyValuesHolder(button, pvhR);
            animation.setRepeatCount(Animation.INFINITE);
            animation.setDuration(1500);
            animation.start();
        }

        @Override
        protected Account doInBackground(Void... params) {
            Account a;
            try {
                a = apiHandler.getAccountInfo();
                return a;
            } catch (final ResponseException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(apiHandler.getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
                return null;
            }
        }

        @Override
        protected void onPostExecute(Account result) {
            animation.setRepeatCount(0);
            if(result!=null){
                a = result;
                showInfo();
                Toast.makeText(getActivity(),"Account synchronization done",Toast.LENGTH_SHORT).show();
            }
        }

    }

我的问题是,当我第一次触发按钮时,动画播放正常,但是当我尝试单击更多次时,AsyncTask将完成其工作,但旋转动画将永远不会播放,直到我完全重新加载片段

我该如何解决?

1 个答案:

答案 0 :(得分:0)

例如,您可以在onPostExecute中结束动画,如下所示:

 @Override
    protected void onPostExecute(Account result) {

        if(animation.isRunning())
            animation.end();           

        ...
        }
    }

这应该比将repeatCount设置为0更有效。