Setting app:layout_behavior programmatically

前端 未结 3 638
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 08:13

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

3条回答
  •  攒了一身酷
    2021-01-31 08:50

    Explanation

    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.


    Example

    (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()
    

提交回复
热议问题