GudniPall
GudniPall

Reputation: 253

Android. Have scrollbar only visible if ScrollView is scrollable

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.

Upvotes: 2

Views: 1000

Answers (2)

Mark P.
Mark P.

Reputation: 56

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.

Upvotes: 2

Raj Datta Manohar
Raj Datta Manohar

Reputation: 167

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.

Upvotes: 2

Related Questions