Configure CoordinatorLayout from code

4.5k Views Asked by At

I'm dynamically injecting a content view into the CoordinatorLayout and would now like to apply a layout_below property to the injected view so that it isn't hidden behind the AppBar.

Is there any way to do this at runtime from code instead of xml properties of the annotation?

2

There are 2 best solutions below

0
On BEST ANSWER

Taking one step back and building the entire view in plain xml, I realized that layout_below is not the property I needed for my use case: placing the content view below the app bar. I did not make this clear in my question though, as I assumed layout_below would be the proper option for that.

In fact, to insert a non scrolling view into the CoordinatorLayout it should first be wrapped with a android.support.v4.widget.NestedScrollView. Then, to avoid its content being hidden behind the app bar, it is necessary to update its behavior to android.support.design.widget.AppBarLayout.ScrollingViewBehavior. Otherwise a default behavior is used which will hide behind the app bar.

val viewToInsert = getLayoutInflater.inflate( id, coordinatorWrapper, false )
val p = viewToInsert.getLayoutParams.asInstanceOf[Coordinator.LayoutParams]
p.setBehavior( new ScrollingViewBehavior )
coordinatorWrapper.addView( viewToInsert, 1, p )
3
On

You could try setting an anchor.

ContentView view = getContentView(); //your view
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) view.getLayoutParams();

params.setAnchorId(R.id.app_bar_layout);
params.anchorGravity = Gravity.BOTTOM; //we will anchor to the bottom line of the appbar
params.gravity = Gravity.BOTTOM; //we want to be BELOW that line
view.setLayoutParams(params);