Scrolling a HorizontalScrollView by clicking buttons on its sides

后端 未结 1 1592
北恋
北恋 2021-01-12 14:16

I am using a HorizontalScrollView within a Fragment. When I scroll this view instead of scrolling the items within HorizontalScrollView

相关标签:
1条回答
  • 2021-01-12 15:11

    If you add the following line of code to your existing handler, your view will scroll right with every button click:

    rightBtn.setOnClickListener(new View.OnClickListener() {
    
        @Override
        public void onClick(View v) {
            hsv.scrollTo((int)hsv.getScrollX() + 10, (int)hsv.getScrollY());
        }
    });
    

    If you'd like it to scroll more smoothly you can use an onTouchListener instead:

    rightBtn.setOnTouchListener(new View.OnTouchListener() {
    
        private Handler mHandler;
        private long mInitialDelay = 300;
        private long mRepeatDelay = 100;
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (mHandler != null)
                        return true;
                    mHandler = new Handler();
                    mHandler.postDelayed(mAction, mInitialDelay);
                    break;
                case MotionEvent.ACTION_UP:
                    if (mHandler == null)
                        return true;
                    mHandler.removeCallbacks(mAction);
                    mHandler = null;
                    break;
            }
            return false;
        }
    
        Runnable mAction = new Runnable() {
            @Override
            public void run() {
                hsv.scrollTo((int) hsv.getScrollX() + 10, (int) hsv.getScrollY());
                mHandler.postDelayed(mAction, mRepeatDelay);
            }
        };
    });
    

    Vary the delays to your liking to get the smoothness and responsiveness you want.

    0 讨论(0)
提交回复
热议问题