HorizontalScrollView with arrows

前端 未结 2 723
无人及你
无人及你 2021-02-04 20:00

I\'m trying to make a scrollable horizontal menu using HorizontalScrollView using the layout shown below. The menu is scrollable using the previous/next arrow buttons or on flin

2条回答
  •  渐次进展
    2021-02-04 20:23

    There is no scroll listener for the HorizontalScrollView. What you can do is add an OnTouchListener to it This will fire continously when the user scrolls, and each time you can use the method getScrollX which returns the int.

    Now 0 mean its left most, to find the right most(max scroll amount), you need to find the width of the child view of the horzontal scroll view. That is found by using the addOnGlobalLayoutListener else the width will always be 0 inside the onCreate method

    Put this code in the onCreate method

    final HorizontalScrollView hs = (HorizontalScrollView)findViewById(R.id.scroll);
    
    ViewTreeObserver vto = hs.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            hs.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
            maxScrollX = hs.getChildAt(0) 
                    .getMeasuredWidth()-getWindowManager().getDefaultDisplay().getWidth();
    
        } 
    });        
    
    hs.setOnTouchListener(new OnTouchListener() {           
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.e("ScrollValue", Integer.toString(hs.getScrollX()));
      if(hs.getScrollX() == maxScrollX){
          Log.e("MaxRight", "MaxRight");    
      }
      return false;
        }
    });
    

提交回复
热议问题