Setting app:layout_behavior programmatically

前端 未结 3 633
爱一瞬间的悲伤
爱一瞬间的悲伤 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()
    
    0 讨论(0)
  • 2021-01-31 08:54

    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

    0 讨论(0)
  • 2021-01-31 09:06

    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.

    0 讨论(0)
提交回复
热议问题