如何以编程方式打开和关闭layout_behavior行为?

时间:2016-02-12 04:56:34

标签: android android-layout android-coordinatorlayout floating-action-button

让我们假装简单的简单案例。我有一个FloatingActionButton,我在其上添加了layout_behavior。我需要能够以编程方式启用或禁用该行为。我怎么做?我最初通过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"/>

1 个答案:

答案 0 :(得分:10)

您可以通过

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

那么你可以直接用setBehavior()设置行为:

params.setBehavior(null);

或者获取您的行为实例并调用方法让它自行禁用(您所做的):

ScrollingFABBehavior behavior =
    (ScrollingFABBehavior) params.getBehavior();
// This is a method you write
behavior.setEnabled(false);