本文介绍了RecyclerView.Adapter通过位置获取ItemView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的适配器中,我调用LayoutManager.ChildAt(position)来获取itemview,但是我得到的视图不是匹配的itemview,并且当我调用notifyItemChanged(position)时,应用程序崩溃了:

In my Adapter, I call LayoutManager.ChildAt(position) to get the itemview, but the view I get is not the matched itemview, and when i call notifyItemChanged(position), app crashes:

E/AndroidRuntime: FATAL EXCEPTION: mainProcess: com.paicaifu.riches, PID: 8502
Java.lang.IllegalArgumentException: Called attach on a child which is not detached: ViewHolder{adb21588 position=0 id=-1, oldPos=-1, pLpos:-1}
at Android.support.v7.widget.RecyclerView$5.attachViewToParent(RecyclerView.java:654)
at android.support.v7.widget.ChildHelper.attachViewToParent(ChildHelper.java:239)
at android.support.v7.widget.RecyclerView.addAnimatingView(RecyclerView.java:1107)
at android.support.v7.widget.RecyclerView.animateChange(RecyclerView.java:3270)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3088)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2917)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
…
at android.view.Choreographer.doCallbacks(Choreographer.java:574)

谢谢,这是我在适配器中的代码:

Thanks,this is my code in the adapter:

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder,
    final int position) {
    if (holder instanceof CardHolder) {
       final CardHolder cardHolder = (CardHolder) holder;
       cardHolder.rootview.setOnClickListener(this);
       cardHolder.rootview.setTag(position);
       cardHolder.rootview.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
         //get last itemview in adapter,but preView isnot match the
         //position,it is the visibable views on screen
         View preView = mLinearLayoutManager.getChildAt(preIndex);
         //change the datasource
         mData.getResult().getCardList().get(preIndex).setOpen(false);
         //update item
         notifyItemChanged(preIndex);//when the item is out of screen,
         //this line will cause crashes
         preIndex = position;
                    }
          });
      }

我只想找到最后一个项目并更改其状态(打开或关闭),当该项目不在屏幕上时,notifyItemChanged(int位置)会出现问题.

I just want find the last item and change it's state(open or close),when the item is out of screen,notifyItemChanged(int position) will appear problem.

推荐答案

这可能为时已晚,但是当您未在其中创建新视图时,通常会发生崩溃称为未分离的子项上的附加" onCreateViewHolder,而是返回已膨胀并已附加的缓存视图.

This is probably a bit too late, but the crash "Called attach on a child which is not detached" typically happens when you do NOT create a new view in onCreateViewHolder and instead return a cached view that's already inflated and attached.

这篇关于RecyclerView.Adapter通过位置获取ItemView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 07:53