Answer the question
In order to leave comments, you need to log in
Strange drag&drop behavior using ItemTouchHelper and RecyclerView. How to fix?
I'm trying to use a RecyclerView with a very handy ItemTouchHelper for my purposes.
All I want is simple "drag & drop" and "swipe-to-dismiss" scripts.
Swipe works correctly, elements are removed correctly in the adapter, the animation also corresponds to what is happening, but “drag & drop” works very strangely. After a long click, the element does not start moving, although the selection is triggered, and the onItemMove method is called in the adapter.
Here's some weird behavior in my RecyclerView
And here's what I'm trying to achieve.
Here's the presenter code, onSelectedChanged and clearView , just to show the selection of items.
addedCitiesRecycler.setLayoutManager(llmAddedCities);
adapterAddedCities = new AdapterAddedCities();
ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.START | ItemTouchHelper.END) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
adapterAddedCities.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
adapterAddedCities.onItemDismiss(viewHolder.getAdapterPosition());
}
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
AdapterAddedCities.ViewHolder holder = (AdapterAddedCities.ViewHolder) viewHolder;
holder.itemView.setBackgroundColor(Color.LTGRAY);
}
super.onSelectedChanged(viewHolder, actionState);
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
AdapterAddedCities.ViewHolder holder = (AdapterAddedCities.ViewHolder) viewHolder;
holder.itemView.setBackgroundColor(0);
}
};
itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(addedCitiesRecycler);
public void onItemDismiss(int position) {
citiesData.remove(position);
notifyItemRemoved(position);
}
public void onItemMove(int fromPosition, int toPosition) {
CityInfo tmp = citiesData.remove(fromPosition);
citiesData.add(toPosition > fromPosition ? toPosition - 1 : toPosition, tmp);
notifyItemMoved(fromPosition, toPosition);
}
Answer the question
In order to leave comments, you need to log in
I updated com.android.support:recyclerview-v7:26.0.0-alpha1
to com.android.support:recyclerview-v7:27.0.0
in the project and everything worked great.
Most likely it was a bug in the library, so if you encounter a similar problem, just update to the latest version and double-check how the RecyclerView behaves.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question