RecyclerView的position==0位置上的View高度為0時馒疹,canScrollVertically方法無法判斷是否已經(jīng)滑動到頂部?

RecyclerView的position==0位置上的View高度為0時乙墙,canScrollVertically方法無法判斷是否已經(jīng)滑動到頂部颖变?

看View中 canScrollVertically 方法的調(diào)用:

    /**
     * Check if this view can be scrolled vertically in a certain direction.
     *
     * @param direction Negative to check scrolling up, positive to check scrolling down.
     * @return true if this view can be scrolled in the specified direction, false otherwise.
     */
    public boolean canScrollVertically(int direction) {
        final int offset = computeVerticalScrollOffset();
        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
        if (range == 0) return false;
        if (direction < 0) {
            return offset > 0;
        } else {
            return offset < range - 1;
        }
    }

這里邊主要調(diào)用了三個方法,分別是computeVerticalScrollOffset()表示縱向滑動的距離伶丐,如果距離為0悼做,表示已經(jīng)滑動到了頂部,computeVerticalScrollRange()指的是整體高度疯特,包括所顯示區(qū)域和屏幕區(qū)域外的高度,computeVerticalScrollExtent()表示的是顯示區(qū)域的高度哗魂。

問題出現(xiàn)的原因

當(dāng)滑動到頂部的時候,computeVerticalScrollOffset()返回的高度一直是大于0的數(shù)漓雅,那么canScrollVertically就一致返回true,表示還沒有滑動到頂部录别。接下來我們RecyclerView中方法computeVerticalScrollOffset()的實(shí)現(xiàn)。?RecyclerView這個方法的實(shí)現(xiàn)是直接調(diào)用LayoutManager的方法computeVerticalScrollOffset邻吞,我使用的LinearLayoutManager,所以直接看這個里邊方法的實(shí)現(xiàn)组题。代碼如下:

@Override
    public int computeVerticalScrollOffset(RecyclerView.State state) {
        return computeScrollOffset(state);
    }

這里又直接調(diào)用的computeScrollOffset方法

    private int computeScrollOffset(RecyclerView.State state) {
        if (getChildCount() == 0) {
            return 0;
        }
        ensureLayoutState();
        return ScrollbarHelper.computeScrollOffset(state, mOrientationHelper,
                findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true),
                findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true),
                this, mSmoothScrollbarEnabled, mShouldReverseLayout);
    }

這里在主要看一下findFirstVisibleChildClosestToStart方法,這個方法主要是用來獲取屏幕中第一個可見的childView抱冷,找到并返回這個childView崔列。

    /**
     * Convenience method to find the visible child closes to start. Caller should check if it has
     * enough children.
     *
     * @param completelyVisible Whether child should be completely visible or not
     * @return The first visible child closest to start of the layout from user's perspective.
     */
    private View findFirstVisibleChildClosestToStart(boolean completelyVisible,
                                                     boolean acceptPartiallyVisible) {
        if (mShouldReverseLayout) {
            return findOneVisibleChild(getChildCount() - 1, -1, completelyVisible,
                    acceptPartiallyVisible);
        } else {
            return findOneVisibleChild(0, getChildCount(), completelyVisible,
                    acceptPartiallyVisible);
        }
    }

下邊是查找第一個可見childView的詳細(xì)代碼,看完下邊的代碼就發(fā)現(xiàn)旺遮,如果第一個childView的高度為0的時候赵讯,會繼續(xù)往下查找,找到第一個不為0的childView并返回耿眉。

View findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible,
                             boolean acceptPartiallyVisible) {
        ensureLayoutState();
        final int start = mOrientationHelper.getStartAfterPadding();
        final int end = mOrientationHelper.getEndAfterPadding();
        final int next = toIndex > fromIndex ? 1 : -1;
        View partiallyVisible = null;
        for (int i = fromIndex; i != toIndex; i += next) {
            final View child = getChildAt(i);
            final int childStart = mOrientationHelper.getDecoratedStart(child);
            final int childEnd = mOrientationHelper.getDecoratedEnd(child);
            //如果第一個childView高度為0边翼,childStart和childEnd都等于0;下邊的條件不成立鸣剪,會繼續(xù)往下邊尋找组底。
            if (childStart < end && childEnd > start) {
                if (completelyVisible) {
                    if (childStart >= start && childEnd <= end) {
                        return child;
                    } else if (acceptPartiallyVisible && partiallyVisible == null) {
                        partiallyVisible = child;
                    }
                } else {
                    return child;
                }
            }
        }
        return partiallyVisible;
    }

computeVerticalScrollOffset()的最終返回值來自這里

/**
     * @param startChild View closest to start of the list. (top or left)
     * @param endChild   View closest to end of the list (bottom or right)
     */
    static int computeScrollOffset(RecyclerView.State state, OrientationHelper orientation,
                                   View startChild, View endChild, RecyclerView.LayoutManager lm,
                                   boolean smoothScrollbarEnabled, boolean reverseLayout) {
        if (lm.getChildCount() == 0 || state.getItemCount() == 0 || startChild == null ||
                endChild == null) {
            return 0;
        }
        //獲取第一個高度不為0的childView的position,如果RecylerView的第一個item高度為0筐骇,那么minPosition的值肯定大于0
        final int minPosition = Math.min(lm.getPosition(startChild),
                lm.getPosition(endChild));
        final int maxPosition = Math.max(lm.getPosition(startChild),
                lm.getPosition(endChild));
        //reverseLayout默認(rèn)是false债鸡,所以itemBefore基本上就是等于minPosition的值
        final int itemsBefore = reverseLayout
                ? Math.max(0, state.getItemCount() - maxPosition - 1)
                : Math.max(0, minPosition);
        if (!smoothScrollbarEnabled) {
            return itemsBefore;
        }
        final int laidOutArea = Math.abs(orientation.getDecoratedEnd(endChild) -
                orientation.getDecoratedStart(startChild));
        final int itemRange = Math.abs(lm.getPosition(startChild) -
                lm.getPosition(endChild)) + 1;
        final float avgSizePerRow = (float) laidOutArea / itemRange;
        //通過返回的值,如果minPosition != 0,返回值都大于0铛纬。
        return Math.round(itemsBefore * avgSizePerRow + (orientation.getStartAfterPadding()
                - orientation.getDecoratedStart(startChild)));
    }

解決方案

要解決這個這個問題厌均,需要將第一個item的高度設(shè)置為1像素就可以啦。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末饺鹃,一起剝皮案震驚了整個濱河市莫秆,隨后出現(xiàn)的幾起案子间雀,更是在濱河造成了極大的恐慌,老刑警劉巖镊屎,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惹挟,死亡現(xiàn)場離奇詭異,居然都是意外死亡缝驳,警方通過查閱死者的電腦和手機(jī)连锯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來用狱,“玉大人运怖,你說我怎么就攤上這事∠囊粒” “怎么了摇展?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長溺忧。 經(jīng)常有香客問我咏连,道長,這世上最難降的妖魔是什么鲁森? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任祟滴,我火速辦了婚禮,結(jié)果婚禮上歌溉,老公的妹妹穿的比我還像新娘垄懂。我一直安慰自己,他們只是感情好痛垛,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布草慧。 她就那樣靜靜地躺著,像睡著了一般榜晦。 火紅的嫁衣襯著肌膚如雪冠蒋。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天乾胶,我揣著相機(jī)與錄音抖剿,去河邊找鬼。 笑死识窿,一個胖子當(dāng)著我的面吹牛斩郎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播喻频,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼缩宜,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起锻煌,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤妓布,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后宋梧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體匣沼,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年捂龄,在試婚紗的時候發(fā)現(xiàn)自己被綠了释涛。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡倦沧,死狀恐怖唇撬,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情展融,我是刑警寧澤窖认,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站愈污,受9級特大地震影響耀态,放射性物質(zhì)發(fā)生泄漏轮傍。R本人自食惡果不足惜暂雹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望创夜。 院中可真熱鬧杭跪,春花似錦、人聲如沸驰吓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽檬贰。三九已至姑廉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間翁涤,已是汗流浹背桥言。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留葵礼,地道東北人号阿。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像鸳粉,于是被迫代替她去往敵國和親扔涧。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,264評論 25 707
  • 簡介: 提供一個讓有限的窗口變成一個大數(shù)據(jù)集的靈活視圖。 術(shù)語表: Adapter:RecyclerView的子類...
    酷泡泡閱讀 5,174評論 0 16
  • 內(nèi)容抽屜菜單ListViewWebViewSwitchButton按鈕點(diǎn)贊按鈕進(jìn)度條TabLayout圖標(biāo)下拉刷新...
    皇小弟閱讀 46,784評論 22 665
  • 因?yàn)槿ソ芗业木壒士菀梗屛易蛱焱砩弦煌砩嫌譀]有時間好好休息弯汰。當(dāng)然嘍終止了所謂的肉番系列。等會兒馬上就要去工作面試湖雹,還...
    夕魄閱讀 229評論 0 0
  • 人人都需要時間管理蝙泼,事情未完成時你是否也和我一樣只知道自責(zé),卻不懂為何磨蹭拖拉劝枣,今天看到一本書《永遠(yuǎn)跟拖拉說再見》...
    大臉貓_Lnn閱讀 347評論 0 1