Marc Marc - 4 months ago 45
Android Question

fab.show() not animated first time after initializing new activity

I am using the floating action button (fab) component from com.android.support:design:23.1.0 Library to generate my app's fabs.

But the first time I load a new activity with fab.hide() and try to make the icon visible through fab.show() after a button was clicked, there is no animation for the fab. This happens only the first time after loading a new activity. When I try that multiple times to hide and show the button, it is animated properly.

What is the issue here? It would be a charm to get it animated also right after an activity is loaded.

Java in activity:

fabSend = (FloatingActionButton) findViewById(R.id.fabSend);
fabSend.hide();


CompoundButton.OnCheckedChangeListener changeChecker = new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// FAB on
fabSend.show();
} else {
// FAB off
fabSend.hide();
}
}
};


Layout.xml

<android.support.design.widget.FloatingActionButton
android:id="@+id/fabSend"
app:borderWidth="0dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_alignParentBottom="true"
android:layout_marginRight="@dimen/fab_margin"
android:layout_marginBottom="54dp"
android:src="@drawable/ic_check_white_24dp" />

Answer

Solved this one finally. I designed a new class to handle the reveal animation with a delay. Grab it here, initialize it and you're good to go. I found a pretty similar animation to the standard fab.show() at 50ms delay on it.

    public static void showFabWithAnimation(final FloatingActionButton fab, final int delay) {
    fab.setVisibility(View.INVISIBLE);
    fab.setScaleX(0.0F);
    fab.setScaleY(0.0F);
    fab.setAlpha(0.0F);
    fab.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            fab.getViewTreeObserver().removeOnPreDrawListener(this);
            fab.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fab.show();
                }
            }, delay);
            return true;
        }
    });
}
Comments