1. 程式人生 > >Android小記:自定義Button導致RecyclerView列表監聽onScroll回撥異常

Android小記:自定義Button導致RecyclerView列表監聽onScroll回撥異常

背景

一天,搭檔告知筆者,在使用了自定義Button後,RecyclerView的onScroll回撥一直被重複回撥,導致程式執行異常。

排查

檢視該自定義控制元件,主要重寫了onDraw方法,發現引發異常的程式碼在於迴圈呼叫了setCompoundDrawables去更新按鈕。

原因

public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top,
            @Nullable Drawable right, @Nullable Drawable bottom) {
        Drawables dr = mDrawables;

        // 忽略程式碼

        resetResolvedDrawables();
        resolveDrawables();
        applyCompoundDrawableTint();
        invalidate();
        requestLayout();
    }

setCompoundDrawables會呼叫requesLayout()導致父控制元件不停重新排版,導致onScroll不停回撥,異常原因找到。