listening to scroll events horizontalscrollview android

Viewed 37290

I am trying to listen to the event when the HorizontalScrollView is scrolled. Tried this but it does not print anything.

HorizontalScrollView headerScrollView = new HorizontalScrollView(this);

    headerScrollView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            Log.i("hv1",event.toString());
            Log.i("hv1","HELLO");
            return false;
        }
    });

The actual problem is, I want to scroll two HorizontalScrollView at a time..ie; both of them need to scroll simultaneously when atleast one of them scrolled. any workaround?

I used the answer below and then tried implementing this but I am not sure how I need to use the methods in the class.

TestHorizontalScrollView headerScrollView = (TestHorizontalScrollView) findViewById(R.id.headerHv); 

Is this the way I need to point to the hsv element in the layout file?

6 Answers

To Avoid the the Api Level Problem... follow this.

scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int scrollY = scrollView.getScrollY(); 
            int scrollX = scrollView.getScrollX();

            if (scrollY > 500) {

            } else {

            }
        }
    });

Based @Dipak's answer In kotlin:

binding.scrollList.viewTreeObserver.addOnScrollChangedListener {
     val X = binding.scrollList.scrollX
     val Y = binding.scrollList.scrollY
}
Related