Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle layout_behavior behavior on and off programmatically?

Let’s pretend the simple case for simplicity. I have a FloatingActionButton on which I add a layout_behavior. I need to be able to enable or disable the behavior programmatically. How do I do that? I originally add the behavior through xml

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/mine"
    app:backgroundTint="@color/colorPrimary"
    app:layout_anchor="@id/default_message"
    app:layout_anchorGravity="end|bottom"
    app:layout_behavior=“mywidget.ScrollingFABBehavior"/>
like image 394
Nouvel Travay Avatar asked Feb 12 '16 04:02

Nouvel Travay


People also ask

How do you set layout behavior programmatically?

You can set the behavior on an instance of CoordinatorLayout. LayoutParams with setBehavior method. To get a proper Behavior object that represents the same thing as @string/appbar_scrolling_view_behavior you should create an instance of AppBarLayout. ScrollingViewBehavior .

What is App Layout_behavior string Appbar_scrolling_view_behavior?

The support library contains a special string resource @string/appbar_scrolling_view_behavior that maps to AppBarLayout. ScrollingViewBehavior , which is used to notify the AppBarLayout when scroll events occur on this particular view. The behavior must be established on the view that triggers the event.

How do I use CoordinatorLayout?

By specifying Behaviors for child views of a CoordinatorLayout you can provide many different interactions within a single parent and those views can also interact with one another. View classes can specify a default behavior when used as a child of a CoordinatorLayout by implementing the AttachedBehavior interface.

What is Coordinator layout in android?

Android CoordinatorLayout is a super-powered FrameLayout. It has a lot more to offer than it seems. It has additional level of control over it's child views. It coordinates the animations and transitions of child views with one another.


1 Answers

You can retrieve the LayoutParams via

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams params = 
    (CoordinatorLayout.LayoutParams) fab.getLayoutParams();

And that point you can either set the behavior directly with setBehavior():

params.setBehavior(null);

Or get your instance of behavior and call a method to have it disable itself (that you make):

ScrollingFABBehavior behavior =
    (ScrollingFABBehavior) params.getBehavior();
// This is a method you write
behavior.setEnabled(false);
like image 67
ianhanniballake Avatar answered Oct 24 '22 10:10

ianhanniballake