Setting behaviour of Floating Action Button programmatically
I

1

5

I'm using the following guide to implement a scroll aware FAB:

https://guides.codepath.com/android/Floating-Action-Buttons#overview

After creating the class, you set up the behaviour by declaring it in XML as follows:

<android.support.design.widget.FloatingActionButton    
app:layout_behavior="com.codepath.floatingactionbuttontest.ScrollAwareFABBehavior" />

Due to how my code is written, I want to set the behaviour programmatically and not in the XML. I have a feeling that this is done with the CoordinatorLayout but I'm drawing a blank.

Any help would be appreciated!

Thanks in advance.

Illeetvilaine answered 12/8, 2015 at 18:33 Comment(0)
C
24

You can use somenthing like this:

CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
p.setBehavior(xxxx);
fab.setLayoutParams(p);
Cartilage answered 13/8, 2015 at 16:38 Comment(3)
It seems that "fab.setLayoutParams(p);" is unnecessary since the "p" points to the LayoutParams object and the calling to "p.setBehavior(xxxx);" is sufficient.Quinta
@AlanZhiliangFeng I can't test it right now; are you sure about this? Of course it makes sense strictly from OOP perspective, but this class represents layout params... changing its properties may require layout recalculation, so it would make sense for the getter to return a mere "copy" which needs to be "reapplied" after modifying.Militarism
By checking the source you can tell that both of you are correct. Yes, it calculates stuff when setting LayoutParams, but also those stuff don't care about the behavior object being changed so I would go with @Gabriele Mariotti's full solution just in case the API changes in the future.Logogram

© 2022 - 2024 — McMap. All rights reserved.