Search code examples
android-studiokotlinscrollview

OnScrollChangeListener for ScrollView


I would like to make a function to intercept a certain scroll at the top of the view. to do this I'm trying to use OnScrollChangeListener. My view contains a ScrollView

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollViewClientPhysique"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/fond"
tools:context=".client.FicheClient">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">**strong text**

and I initialize addOnScrollChangedListener in a function I call inside onCreateView

    fun initializeInfiniteScroll(){
    val scrollView = myView.findViewById<View>(R.id.scrollViewClientPhysique) as ScrollView

    scrollView.viewTreeObserver.addOnScrollChangedListener {
        if (scrollView != null) {
            val view = scrollView.getChildAt(scrollView.childCount - 1)
            val diff =
                view.bottom + scrollView.paddingBottom - (scrollView.height + scrollView.scrollY)

            if (diff == 0) {
                // do stuff
                }
            }
        }
     }

but when when I scroll the view I don't enter addOnScrollChangedListener to intercept how many dp the scroll is.

what am I doing wrong?


Solution

  • Please update your ScrollChangedListener as mentioned below.

        public class MainActivity extends AppCompatActivity implements View.OnTouchListener,
           ViewTreeObserver.OnScrollChangedListener {
           ScrollView scrollView;
           @Override
           protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              scrollView = findViewById(R.id.scrollView);
              scrollView.setOnTouchListener(this);
              scrollView.getViewTreeObserver().addOnScrollChangedListener(this);
           }
           public void onScrollChanged(){
              View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
              int topDetector = scrollView.getScrollY();
              int bottomDetector = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY());
              //TODO: Just added for testing/understanding. Please add/replace your own logic..
              if(bottomDetector == 0 ){
                 Toast.makeText(this,"Scroll View bottom reached",Toast.LENGTH_SHORT).show();
              }
              if(topDetector <= 0){
                 Toast.makeText(this,"Scroll View top reached",Toast.LENGTH_SHORT).show();
              }
           }
           @Override
           public boolean onTouch(View v, MotionEvent event) {
              return false;
           }
        }