I have a coordinator layout with a recyclerview which I would like to add programmatically. The reason why it\'s added programatically is because different fragments which infla
Behavior
is a parameter of the CoordinatorLayout.LayoutParams
. 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.
(this is a cleaned up version of my previous edits to the original answer)
First you will have to get an instance of a child View
of your CoordinatorLayout
.
Let me get this clear: it is NOT the CoordinatorLayout
itself. childView
is CoordinatorLayout's
child.
//e.g. like this:
val childView: View = findViewById(R.id.child_view)
Assuming the childView
is already attached to the CoordinatorLayout
(so it already has LayoutParams
), you can do:
val params: CoordinatorLayout.LayoutParams = yourView.layoutParams as CoordinatorLayout.LayoutParams
params.behavior = AppBarLayout.ScrollingViewBehavior()
yourView.requestLayout()
To enable and disable layout_behavior
programatically with kotlin use this code :
fun enableLayoutBehaviour() {
val param: CoordinatorLayout.LayoutParams = swipeRefreshView.layoutParams as CoordinatorLayout.LayoutParams
param.behavior = AppBarLayout.ScrollingViewBehavior()
}
fun disableLayoutBehaviour() {
val param: CoordinatorLayout.LayoutParams = swipeRefreshView.layoutParams as CoordinatorLayout.LayoutParams
param.behavior = null
}
Note: replace swipeRefreshView with your view
Accepted answer is correct but the provided code is not compilable. So here is a complete example
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams)
view.getLayoutParams();
params.setBehavior(new AppBarLayout.ScrollingViewBehavior(view.getContext(), null));
2nd param is AttributeSet
and it is fine to have it as null
although it is not marked as Nullable
in support lib.