Setting behaviour of Floating Action Button programmatically

Adam picture Adam · Aug 12, 2015 · Viewed 9.1k times · Source

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.

Answer

Gabriele Mariotti picture Gabriele Mariotti · Aug 13, 2015

You can use somenthing like this:

CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
p.setBehavior(xxxx);
fab.setLayoutParams(p);