Search code examples
androidbindingscrollviewlistener

Android which attribute set to binding onScrollChanged()


I want to execute onScrollChangeListner when binding views. But I don't know which attribute set to Android:.... in layout.

I create horizontal scrollview, write onScrollChangeListner, next I add this view to binding. Before I add view to binding, scrollview has execute listener and I saw changes in him. Maybe I must add this listener to layout? But I don't know how.

Code in class:

HorizontalScrollView horizontalScrollView = view.findViewById(R.id.scroll_view);
        horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
.
. execute code
.
}

Code in layout:

   <data>

        <variable
            name="sample"
            type=Class with my method />
    </data>

android:onScroll="@{() -> sample.onScrollChanged()}"

Found data binding errors. ****/ data binding error ****msg:Cannot find the setter for attribute 'android:onScroll' with parameter type lambda on android.widget.HorizontalScrollView. ****\ data binding error ****


Solution

  • you can do this with BindingAdapter

        @JvmStatic
        @BindingAdapter("onScrolled")
        fun setOnScroll(horizontalScrollView: HorizontalScrollView) {
            horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                    @Override
                    public void onScrollChanged() { }
            )
        }
    
        onScrolled="@{() -> sample.onScrollChanged()}"