大家在自定義Android ViewGroup的時(shí)候默認(rèn)是不會(huì)draw滾動(dòng)條的,但是網(wǎng)上這方面的資料比較少。
當(dāng)我們想要顯示滾動(dòng)條時(shí)需要調(diào)用:
awakenScrollBars();
但是,你以為這就完了?
其實(shí)這樣做并無(wú)卵用。
然后就開(kāi)始百度。。
百度了一圈也沒(méi)結(jié)果。
關(guān)鍵詞換成英文終于搜到一篇7年前的stackoverflow
https://stackoverflow.com/questions/9515461/scroll-bar-to-custom-viewgroup
這里是說(shuō):
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 .
要覆寫(xiě)這倆方法。
然后我打開(kāi)ScrollView源碼,直接復(fù)制過(guò)來(lái)。。簡(jiǎn)單修改了下。
@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;
}
這樣就完美的顯示了滾動(dòng)條。