今天解决了一个困扰我一天的BUG。
我要用RecyclerView+PagerSnapHelper做一个类似无限循环切换的ViewPager。我采用的最简单的方法将adapter里面的getItemCount()调大;用recycleViewRun.scrollToPosition(333332);移到中间位置。
页面为2张时,慢速切换没问题,快速切换时会出现下面的问题。
java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6796)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1331)
at android.support.v7.widget.LinearLayoutManager.scrollHorizontallyBy(LinearLayoutManager.java:1063)
at android.support.v7.widget.RecyclerView.scrollStep(RecyclerView.java:1829)
at android.support.v7.widget.RecyclerView$SmoothScroller.onAnimation(RecyclerView.java:11651)
at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:5149)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:543)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
搜了很多答案,一种是inflater.inflate参数改为null或者false。我用的参数就是false。问题没有解决。
直到我搜到了一个博主的回答,才解决了问题。非常感谢jiluyixia
我的原因应该是:快速切换时,新建的布局还在父布局里面,没有移除。我在onCreateViewHolder里面添加了如下语句,解决了。
ViewGroup elViewGroup = (ViewGroup)view.getParent();
if (elViewGroup !=null) {
elViewGroup.removeView(view);
}
return new RecyclerHolder(view);