我正在尝试将RecyclerView
withItemTouchHelper
用于基本的“拖放”和“滑动关闭”实现。滑动正常,适配器中的项目正确删除,动画正确,但“拖放”行为非常奇怪。长按后视图没有移动,但是适配器中的交换项目是正确的。
我的演示者中的这段代码,onSelectedChanged 和 clearView 只是为了清楚地演示如何选择项目。
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);
}