Android: Enable Scrollbars in Custom View

前端 未结 2 1882
北海茫月
北海茫月 2021-01-03 00:00

I have implemented a custom Layout that extends RelativeLayout. It displays lots of different elements that are created at run-time and is scrollable in both dimensions usin

相关标签:
2条回答
  • 2021-01-03 00:04

    Just had this same problem and finally figured it out.

    The "problem" is that you are extending RelativeLayout, which is a subclass of ViewGroup. I found that I had no problem doing what you described in your question to get a custom View to display scrollbars, but when I extended ViewGroup or one of its subclasses, no scrollbars appeared.

    I finally remembered that ViewGroups, by default, don't draw themselves. I added one line to my custom ViewGroup constructor: setWillNotDraw(false);

    What do you know, the scrollbars appeared!

    Hope that helps.

    0 讨论(0)
  • 2021-01-03 00:23

    Fyi, on Android 3.2/Google TV, and Android 3.2.1/Tablet, the <declare-styleable/> part of the solution is not optional when extending ViewGroup. The problem seems to be that none of the scrollbar drawables and sizes used by View to draw the scrollbars are loaded unless all of the corresponding scrollbar properties in the <declare-styleable/> are set. Failing to set some significant number of those properties results in a null pointer exception during layout on 3.2. I also suspect that the GridView/ListView/AbsListView/AdapterView series of classes don't set the horizontal scrollbar attributes, if that's what you happen to be chasing.

    The general steps seem to be:

    • Use a <declare-styleable/> (as described above).
    • Call initScrollbars early in your constructor (as described above).
    • Call setHorizontalScrollbarEnabled/setrVerticalScrollBarEnbled after calling initScrollbars.
    • Implement the set of three computeHorizontalScrollXXX, and computeVerticalScrollXXX as appropriate.
    • make frequent calls to awakenScrollBars() as appropriate to get the scrollbars to display.
    • Most probably, a call to setWillNotDraw(false) has to be made in the constructor. Scrollbar drawing is implemented in View; but I do in fact call this method myself.
    • consider a call to setScrollBarStyle to control placement of the scrollbars. Most useful custom views that scroll will end up clipping to the padding margins, which will screw up View's drawing of the scrollbars if they are placed outside the padding rectangle, since We don't have access to the same hidden methods in View that stock android views do.

    I think that's it. Chances of all that working on Android 6.0... slim to none. :-/

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