2

Is there a simple way to have the scrollbar in ScrollView only visible if the view is scrollable?

I know it's possible to achieve this by comparing the height of the ScrollView and the ViewGroup inside it and then calling ScrollView.setScrollbarFadingEnabled(false); but it's a lot of overhead and i feel like there should be a simpler and cleaner way.

2 Answers 2

2

You are describing the normal behaviour of a ScrollView. If the ScrollView is not scrollable the ScrollBar won't appear. Even android:fadeScrollbars="false" won't take any effect if the view isn't scrollable. Maybe the only child of the ScrollView itself is to big to fit in the viewport (or the ScrollView container) In your case the ScrollView seems to have always a scrollbar. You could test it by putting a simple TextView as a child in the ScrollView and adjusting the height.

Sign up to request clarification or add additional context in comments.

Comments

2

Use a ViewTreeObserver to get the heights, because it will be called at the moment the layout / view is changing the visibility, otherwise the heights could be 0.

ScrollView scrollView = (ScrollView)findViewById(R.id...);
ViewTreeObserver observer = scrollView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int viewHeight = scrollView.getMeasuredHeight();
        int contentHeight = scrollView.getChildAt(0).getHeight();
        if(viewHeight - contentHeight < 0) {
           ScrollView.setVerticalScrollBarEnabled(false);
        }
    } 
});

This is a clean solution IMO and there is no easier way than this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.