Search code examples
androidandroid-layoutkotlinandroid-scrollview

I want to trigger OnScrollChangeListener for certain space scrolled


I have a scrollView that needs to hide a keyboard when I drag certain Y offset , currently it will always close my keyboard when I enter an edittext but what I want to do is to execute the hideKeyboard() when for example the view has been scrolled Y units

binding.scrollView.setOnScrollChangeListener { view, i, i2, i3, i4 ->
            hideKeyboard()
        }

I want to add a condition like this

binding.scrollView.setOnScrollChangeListener { view, i, i2, i3, i4 ->
            if(position_dragged_in_Y > some_value)
            hideKeyboard()
        }

How do I do this ? thanks


Solution

  • When setting an OnScrollChanceListener, I got the following attributes:

        scrollview.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
        }
    

    So, OnScrollChangeListener already gives us the current Position of the scrollY Position. To set a condition like (if scrollY >= someYPosition), you could add an invisible View inside your scrollview, like this:

            <View
                android:id="@+id/myInvisibleViewForCondition"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
    

    Then, to get the absolute Y Position of our myInvisibleViewForCondition we use the following extension function:

    fun View.getLocationOnScreen(): Point {
        val location = IntArray(2)
        this.getLocationOnScreen(location)
        return Point(location[0],location[1])
    }
    

    Now we can start to work on the condition:

        scrollview.setOnScrollChangeListener { _, _, scrollY, _, _ ->
            val absolutPositionOfInvisibleView = myInvisibleViewForCondition.getLocationOnScreen()
            val yPositionOfInvisibleView = absolutPositionOfInvisibleView.y
            if (scrollY > yPositionOfInvisibleView) {
                hideKeyboad()
            }
        }
    

    I couldn't test the functionality, so let me now, if this works.

    Cheers