大家在自定义Android ViewGroup的时候默认是不会draw滚动条的,但是网上这方面的资料比较少。
当我们想要显示滚动条时需要调用:
awakenScrollBars();
但是,你以为这就完了?
其实这样做并无卵用。
然后就开始百度。。
百度了一圈也没结果。
关键词换成英文终于搜到一篇7年前的stackoverflow
https://stackoverflow.com/questions/9515461/scroll-bar-to-custom-viewgroup
这里是说:
you have to call `awakenScrollBars()` ,which will trigger the scrollbars to draw
on your custom viewGroup.
([more details](http://developer.android.com/reference/android/view/View.html#awakenScrollBars%28%29)) and the vertical scrollbar enabled has to be true `setVerticalScrollBarEnabled()`
Also you have to override functions `computeVerticalScrollExtent()` and `computeVerticalScrollRange` to set thumb's size and scrollbar scroll range .
要覆写这俩方法。
然后我打开ScrollView源码,直接复制过来。。简单修改了下。
@Override
protected int computeVerticalScrollOffset() {
return Math.max(0, super.computeVerticalScrollOffset());
}
@Override
protected int computeVerticalScrollRange() {
final int count = getChildCount();
final int contentHeight = getHeight() ;
if (count == 0) {
return contentHeight;
}
int scrollRange = child.getBottom();
final int scrollY = getScrollY();
final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
if (scrollY < 0) {
scrollRange -= scrollY;
} else if (scrollY > overscrollBottom) {
scrollRange += scrollY - overscrollBottom;
}
return scrollRange;
}
这样就完美的显示了滚动条。
网友评论