Get CoordinatorLayout Behavior in Constructor of Custom View

310 views Asked by At

I have created a custom view to handle my bottom sheet implementation. I have tried to retrieve the bottomsheet behavior using BottomSheetBehavior.from( this ) but since I need the behavior in the constructor, this is not yet initalized.

For now, I've managed a workaround using postDelayed runnable at 1ms to get the behavior and do what I need but that is clearly a hack.

I have been unable to find any other ways to get the behavior.

[EDIT]

After looking a bit deeper, this not being initialized does not seem to be the problem. The problem is that the LayoutParams are not an instance of CoordinatorLayout.LayoutParams when BottomSheetBehavior.from is called directly from the constructor but they are CoordinatorLayout.LayoutParams when called from the runnable created in the constructor.

1

There are 1 answers

0
cren90 On BEST ANSWER

After looking through the View documentation a bit more, I moved the calls from the view's constructor to its onAttachedToWindow method.

I find this to be much cleaner than using a runnable.