Alexander Farber
Alexander Farber

Reputation: 22988

FAB does not animate - test code and screenshot attached

I have prepared a simple test project at GitHub for my question:

app screenshot

I am trying to show/hide a FloatingActionButton (aka FAB) every 5 seconds by the following code in MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mFab = (FloatingActionButton) findViewById(R.id.fab);

    mInAnimation = AnimationUtils.makeInAnimation(this, false);
    mInAnimation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationEnd(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationStart(Animation animation) {
            mFab.setVisibility(View.VISIBLE);
        }
    });

    mOutAnimation = AnimationUtils.makeOutAnimation(this, true);
    mOutAnimation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationEnd(Animation animation) {
            mFab.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationStart(Animation animation) {
        }
    });

    run();
}

The Runnable output ("Toggle animation") appears every 5 seconds in ADB logs, but the FAB is always visible:

@Override
public void run() {
    Log.d("MyCoordinator", "Toggle animation");
    mFab.setAnimation(mFab.isShown() ? mOutAnimation : mInAnimation);
    mHandler.postDelayed(this, 5000);
}

Does anybody please know, what is missing here?

Also I am curious, if it's possible to define the above animations in the activity_main.xml instead of Java code.

Upvotes: 1

Views: 379

Answers (1)

Blackbelt
Blackbelt

Reputation: 157447

I would rather use mFab.startAnimation(mFab.isShown() ? mOutAnimation : mInAnimation) than mFab.setAnimation(mFab.isShown() ? mOutAnimation : mInAnimation);. With setAnimation you have to define the start time of your animation (which is probably what you are missing)

Upvotes: 1

Related Questions