androidandroid-scroll

Programmatically find out scrollbar size


I am using a custom view that I add scrollbars to like this:

setHorizontalScrollBarEnabled(true);
setVerticalScrollBarEnabled(true);

TypedArray a = context.obtainStyledAttributes(R.styleable.View);
initializeScrollbars(a);
a.recycle()

Now is there a way to find out the thickness of the scrollbars in pixels? For the vertical scrollbar I'd like to find out the width and for the horizontal scrollbar I'd like to find out the height, both in pixels.

Is there a way to do this programmatically?


Solution

  • To answer my own question, there are several ways to get the scrollbar size programmatically:

    View.getScrollBarSize() [API 16]
    ViewConfiguration.getScaledScrollBarSize() [API 3]
    View.getHorizontalScrollbarHeight()
    View.getVerticalScrollbarWidth()
    

    Interestingly, only the latter two worked for me and returned the correct size (8 pixels). The upper two returned 20 pixels which didn't match the actual scrollbar size of 8 pixels. Maybe this is related to the fact that I'm programmatically adding scrollbars to a custom view in a rather unorthodox way (see here). Anyway, using getHorizontalScrollbarHeight() and getVerticalScrollbarWidth() solved the issue for me.