您的位置:首页 > 运维架构

RecyclerView中的坑RecyclerView$LayoutManager.stopSmoothScroller()报错

2016-04-14 16:30 489 查看
转载请注明出处,http://blog.csdn.net/wyyalc/article/details/51152625

首先说说,这个错误是在activity关闭或fragment销毁时报错的

(本来打算在使用到RecyclerView时调用其setLayoutManager(LayoutManager layout)方法,但是如果在销毁时没有设置,就会出现此错误)

下面是错误信息:

04-14 16:07:54.331: E/AndroidRuntime(27973): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.stopSmoothScroller()' on a null object reference


错误的信息很明确,on a null object reference,这类错误的原因是,这个方法的调用对象为空,而在这个地方就是RecyclerView$LayoutManager对象为空

我们先看看RecyclerView的方法onDetachedFromWindow()

@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
mFirstLayoutComplete = false;
stopScroll();
mIsAttached = false;
if (mLayout != null) {
mLayout.onDetachedFromWindow(this, mRecycler);
}
removeCallbacks(mItemAnimatorRunner);
}


方法里边调用了 stopScroll(),我们去瞅瞅这个方法

public void stopScroll() {
setScrollState(SCROLL_STATE_IDLE);
stopScrollersInternal();
}


很简单直接调用了 stopScrollersInternal(),进入这个方法

private void stopScrollersInternal() {
mViewFlinger.stop();
mLayout.stopSmoothScroller();
}


我们看到这里直接调用了mLayout.stopSmoothScroller(),而并没有判断mLayout是否为空,

在RecyclerView定义了一个变量

private LayoutManager mLayout;

所以出现这个错误;

总之

只要在布局中出现RecyclerView,在销毁之前必须调用setLayoutManager方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  RecyclerVi stopSmooth