2016-10-10 158 views
0

好吧,所以它有點複雜,我有一個自定義的RecyclerView適配器,並且在OnBindViewHolder方法中,我想根據一些不同的變量從recyclerview中刪除當前項目,但是當我從ArrayList中刪除該項目並調用notifyDataSetChanged();時,得到: java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling從RecyclerView Android的OnBindViewHolder方法列表中刪除項目

如何從onBindViewHolder中的RecyclerView中刪除項目? ,我不想在設置適配器之前這樣做,因爲recyclerview中的每個項目都有一個子列表,如果子列表爲空,我想刪除該項目。感謝您的任何想法併爲糟糕的英語感到抱歉。

回答

0

請按照以下方法使用,如this所示。

private List<DetectedIssue> issues = new ArrayList<DetectedIssue>(); 

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { 
// - get element from your dataset at this position 
// - replace the contents of the view with that element 

    holder.button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      try { 
       issues.remove(position); 
       notifyItemRemoved(position); 
       //this line below gives you the animation and also updates the 
       //list items after the deleted item 
       notifyItemRangeChanged(position, getItemCount()); 

      } catch (SQLException e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

@Override 
public int getItemCount() { 
    return issues.size(); 
} 

PS:如可以從documentation可以看出它是壞的做法是使用notifyDataSetChanged()如果僅一個項被添加,移動或不必要的過程運行中移除。

此事件並未指定數據集已更改的內容,強制任何觀察者都假定所有現有項目和結構可能不再有效。 LayoutManagers將被迫完全重新綁定並重新佈局所有可見的視圖。

如果您希望更改某些活動中的基礎數組列表,則必須使用接口與活動進行通信以更改數組列表。