如何正确使用ItemTouchHelper

时间:2017-10-01 18:27:45

标签: java android android-recyclerview itemtouchhelper

我正在尝试使用RecyclerViewItemTouchHelper进行基本的“拖动”操作放弃“和”轻扫以解雇“实施。 滑动工作正常,项目在适配器中正确删除,动画是正确的,但“拖动& “行为很奇怪。长时间单击视图后没有移动,但是适配器中的交换项是正确的。

this is how it works in my RecyclerView

and this is what I want

此演示文稿中的代码,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);
}

1 个答案:

答案 0 :(得分:1)

我已在build.gradle中将com.android.support:recyclerview-v7:26.0.0-alpha1更新为com.android.support:recyclerview-v7:27.0.0并且工作正常。

我认为这是库中的错误,所以如果您遇到同样的问题,只需将库更新到最新版本。