自定義ViewGroup顯示scrollbar(滾動(dòng)條)

大家在自定義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)條。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容