Search code examples
androidandroid-layoutfloating-action-button

set FAB anchor gravity dynamically


I need to be able to change the app:layout_anchorGravity="center" of the FAB from center to bottom|start from the code. I've found this example:

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

but it's for setting the anchor and not the anchor gravity.


Solution

  • The CoordinatorLayout.LayoutParams class has the anchorGravity field for that. For example:

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
    lp.anchorGravity = Gravity.BOTTOM | GravityCompat.START;
    fab.setLayoutParams(lp);