Android ItemTouchHelper onChildDraw 使 itemView return 回到原来的位置

Android ItemTouchHelper onChildDraw make itemView return to its original position

我在 SimpleItemTouchHelper class 方法 onChildDraw 中重写了以下方式:

@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
    if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
        float width = (float) viewHolder.itemView.getWidth();
        float alpha = 1.0f - Math.abs(dX) / width;
        viewHolder.itemView.setAlpha(alpha);
        viewHolder.itemView.setTranslationX(dX);
    } else {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY,
                actionState, isCurrentlyActive);
    }
}

这只会在您向左或向右滑动时启用淡入动画。

在我的适配器中,我实现了 ItemTouchHelperAdapter 并按以下方式覆盖 onItemDismiss 以显示 AlertDialog 以确认您是否要删除所选元素:

public class TeambuilderAdapter extends RecyclerView.Adapter<TeambuilderAdapter.ViewHolder> implements ItemTouchHelperAdapter {

    @Override
    public void onItemDismiss(int position) {

        DialogInterface.OnClickListener dialogClickListener =(dialog, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                mData.remove(position);
                notifyItemRemoved(position);
                ((PokemonTeambuilderTabActivity) mContext).refreshTeamList();
            }
        };

        new AlertDialog . Builder (mContext)
                .setTitle(mContext.getString(R.string.remove_team))
                .setMessage(mContext.getString(R.string.remove_team_question))
                .setPositiveButtonIcon(ContextCompat.getDrawable(mContext, R.drawable.ic_baseline_check_circle_14))
                .setPositiveButton(mContext.getString(R.string.confirm), dialogClickListener)
                .setNegativeButtonIcon(ContextCompat.getDrawable(mContext, R.drawable.ic_baseline_cancel_14))
                .setNegativeButton(mContext.getString(R.string.decline), dialogClickListener)
                .show();

    }
...
}

一切正常,问题在于,如果我按下取消按钮,滑动的项目会消失,只有在我重新输入 activity 时才会再次出现。

当我按下取消或离开对话框时,如何恢复原来的位置?

您的 dialogClickListener 未处理取消按钮操作。
对于取消操作,获取您的 itemView 和 setTranslationX(0) 以及 setAlpha(1).