Set layout_anchor at runtime on FloatingActionButton

Bignadad picture Bignadad · Jul 23, 2015 · Viewed 8.1k times · Source

I am trying to animate a android.support.design.widget.FloatingActionButton that is pinned to my AppBarLayout. I can set it fine within the layout xml and it shows up fine. However i am doing a Shared Element Transition to this layout and the FAB is showing up before the view is set. I tried to set the visibility to GONE and INVISIBLE but they seem to be disregarded if the layout_anchor is set in the layout xml. Is there anyway around this?

I would like the activity to load with the shared element transition then fade in my FAB. I just can't hide the FAB on load. I could do it without using the layout_anchor but prefer to keep that if possible.

Answer

Gabriele Mariotti picture Gabriele Mariotti · Jul 23, 2015

If you have a FAB with the the app:layout_anchor attribute, and you want to set the visibility you should use something like this:

CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
params.setAnchorId(View.NO_ID);
fab.setLayoutParams(params);
fab.setVisibility(View.GONE);

If you want to set theapp:layout_anchor dinamically you can use the same code:

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