我有一個簡單的RecyclerView顯示項目。目前,從RecyclerView.Adapter
,我可以使用以下方法成功刪除項目。從對話框中刪除RecyclerView項目不更新
private void removeItem(int pos) {
filteredDataSet.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, getItemCount());
}
我把它從ViewHolder
.The動畫的onClick()
功能正常工作,該視圖更新,一切正常。非常標準的RecyclerView。
但是,我想要做的是讓用戶通過Dialog
驗證項目刪除。下面是該對話框的基本設置(如果去掉不必要的代碼):
...
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Delete this item?");
builder.setView(layout);
final int itemPos = pos;
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeItem(itemPos);
}
});
...
所以,我只是移動的方法調用到對話框的onClickListener
。
我遇到的問題是,當RecyclerView消除已刪除的項目時,它將其動畫返回到完全相同的位置,並且列表保持不變。就像它仍然在那裏。
但是,如果我向下滾動,我得到一個出界錯誤:
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position
這意味着它實際上並不存在,而當回頭進入查看一遍,就不見了。所以,它好像被緩存了,而不是更新適配器或數據集。我讀出它需要所謂的主線程上,所以我修改了我的方法是:
private void removeItem(int pos) {
final int itemPos = pos;
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
filteredDataSet.remove(itemPos);
notifyItemRemoved(itemPos);
notifyItemRangeChanged(itemPos, getItemCount());
}
};
handler.post(runnable);
}
它仍然沒有工作,我不知所措。我懷疑這是一個線程問題,但不知道從哪裏開始。
嘗試調製。代碼是正確的從列表中刪除位置。 我認爲問題是你從哪裏調用removeItem方法的按鈕的onclick事件,這裏只是檢查你是否傳遞正確的項目位置? –
什麼是filteredDataSet?它有什麼價值? –
@ keyur9779:傳遞的位置是正確的。 @quick學習者:filteredDataSet是通過SQL數據庫填充的'List <>'。它按照需要運行(當然,減去提到的問題)。 – anthony