RecyclerViewでスワプで削除をするためには、ItemTouchHelperのonSwiped / onChildDrawで以下のように記載します。
final ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.LEFT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return true; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { final int index = viewHolder.getAdapterPosition(); //該当のデータを削除する DeleteData(viewHolder.getAdapterPosition()); //戻すためのスナックバーの表示 Snackbar snackbar = Snackbar.make(mListView, R.string.snackbar_redo_message, Snackbar.LENGTH_LONG); snackbar.setAction(R.string.undo, v -> { //Undo処理を行う }); snackbar.show(); } @Override public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { return ItemTouchHelper.LEFT; } @Override public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); View itemView = viewHolder.itemView; int backgroundCornerOffset = 20; //so background is behind the rounded corners of itemView int iconMargin = (itemView.getHeight() - mDeleteIcon.getIntrinsicHeight()) / 2; int iconTop = itemView.getTop() + (itemView.getHeight() - mDeleteIcon.getIntrinsicHeight()) / 2; int iconBottom = iconTop + mDeleteIcon.getIntrinsicHeight(); if(dX == 0){ // スワイプしないなら表示をクリアする mDeleteBackground.setBounds(0, 0, 0, 0); return; } if (dX > 0) { // 右にスワイプするときの処理 int iconLeft = itemView.getLeft() + iconMargin + mDeleteIcon.getIntrinsicWidth(); int iconRight = itemView.getLeft() + iconMargin; mDeleteIcon.setBounds(iconLeft, iconTop, iconRight, iconBottom); mDeleteBackground.setBounds(itemView.getLeft(), itemView.getTop(), itemView.getLeft() + ((int) dX) + backgroundCornerOffset, itemView.getBottom()); } else if (dX < 0) { // 左へスワイプするときの処理 int iconLeft = itemView.getRight() - iconMargin - mDeleteIcon.getIntrinsicWidth(); int iconRight = itemView.getRight() - iconMargin; mDeleteIcon.setBounds(iconLeft, iconTop, iconRight, iconBottom); mDeleteBackground.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset, itemView.getTop(), itemView.getRight(), itemView.getBottom()); } mDeleteBackground.draw(c); mDeleteIcon.draw(c); } });
0 件のコメント :
コメントを投稿