HorizontalScrollView with arrows

前端 未结 2 716
无人及你
无人及你 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;
        }
    });
    
    0 讨论(0)
  • 2021-02-04 20:47

    Use getScrollX() of the LinearLayout inside your scroller to determine which is the leftmost corner on screen. If it's 0, then left arrow should be disabled.

    For the right arrow, retrieve the drawing rectangle's width, add getScrollX() and compare that to getMeasuredWidth (), if it's the same, you're at the right, no need for the right arrow.

    So your code will look like this:

    if (homeMenu.getScrollX()==0) {
      hideLeftArrow();
    } else {
      showLeftArrow();
    }
    if (homeMenu.getDrawingRect().right == homeMenu.getMeasuredWidth()) {
      hideRightArrow();
    } else {
      showRightArrow();
    }
    

    Of course you will have to put this in an event listener. I can only think of using your own HorizontalScrollView class, with the onScroll() method overwritten to perform the checks above, see this post.

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