当前位置: 首页 > 知识库问答 >
问题:

是否在滑动时从recyclerview中编辑并删除项目?[副本]

子车凌龙
2023-03-14

Iam正在尝试编辑和删除RecyclerView中的项目。当我刷回收视图,我应该得到两个按钮。一个按钮用于编辑数据,另一个按钮用于从RecyclerView中删除数据。

public class Bills_Adapter extends RecyclerView.Adapter<Bills_Adapter.BillHolder> implements Filterable
{

    Context context;
    List<Manager_Bill_Model> bill_lists;

    public Bills_Adapter(Context context, List<Manager_Bill_Model> bill_lists)
    {
        this.context = context;
        this.bill_lists = bill_lists;
    }

    @Override
    public BillHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
    {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_bills, viewGroup, false);
        BillHolder billHolder = new BillHolder(v);
        return billHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull BillHolder billHolder, int i)
    {
        billHolder.tview_billNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                final Dialog dialog = new Dialog(context);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.activity_bill_dialog);
                dialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();

            }
        });

    }

    @Override
    public int getItemCount() {
        return 50;
    }

    @Override
    public Filter getFilter() {
        return null;
    }

    public class BillHolder extends RecyclerView.ViewHolder
    {
        TextView tview_billNumber;

        public BillHolder(@NonNull View itemView)
        {
            super(itemView);
            tview_billNumber = itemView.findViewById(R.id.tview_billNumber);
        }
    }
}

共有1个答案

董子平
2023-03-14
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.Rect;
    import android.graphics.RectF;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.helper.ItemTouchHelper;
    import android.util.Log;
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    import android.view.View;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Queue;

    public abstract class SwipeHelper extends ItemTouchHelper.SimpleCallback {

        public static final int BUTTON_WIDTH = YOUR_WIDTH_IN_PIXEL_PER_BUTTON
        private RecyclerView recyclerView;
        private List<UnderlayButton> buttons;
        private GestureDetector gestureDetector;
        private int swipedPos = -1;
        private float swipeThreshold = 0.5f;
        private Map<Integer, List<UnderlayButton>> buttonsBuffer;
        private Queue<Integer> recoverQueue;

        private GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                for (UnderlayButton button : buttons){
                    if(button.onClick(e.getX(), e.getY()))
                        break;
                }

                return true;
            }
        };

        private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent e) {
                if (swipedPos < 0) return false;
                Point point = new Point((int) e.getRawX(), (int) e.getRawY());

                RecyclerView.ViewHolder swipedViewHolder = recyclerView.findViewHolderForAdapterPosition(swipedPos);
                View swipedItem = swipedViewHolder.itemView;
                Rect rect = new Rect();
                swipedItem.getGlobalVisibleRect(rect);

                if (e.getAction() == MotionEvent.ACTION_DOWN || e.getAction() == MotionEvent.ACTION_UP ||e.getAction() == MotionEvent.ACTION_MOVE) {
                    if (rect.top < point.y && rect.bottom > point.y)
                        gestureDetector.onTouchEvent(e);
                    else {
                        recoverQueue.add(swipedPos);
                        swipedPos = -1;
                        recoverSwipedItem();
                    }
                }
                return false;
            }
        };

        public SwipeHelper(Context context, RecyclerView recyclerView) {
            super(0, ItemTouchHelper.LEFT);
            this.recyclerView = recyclerView;
            this.buttons = new ArrayList<>();
            this.gestureDetector = new GestureDetector(context, gestureListener);
            this.recyclerView.setOnTouchListener(onTouchListener);
            buttonsBuffer = new HashMap<>();
            recoverQueue = new LinkedList<Integer>(){
                @Override
                public boolean add(Integer o) {
                    if (contains(o))
                        return false;
                    else
                        return super.add(o);
                }
            };

            attachSwipe();
        }


        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            int pos = viewHolder.getAdapterPosition();

            if (swipedPos != pos)
                recoverQueue.add(swipedPos);

            swipedPos = pos;

            if (buttonsBuffer.containsKey(swipedPos))
                buttons = buttonsBuffer.get(swipedPos);
            else
                buttons.clear();

            buttonsBuffer.clear();
            swipeThreshold = 0.5f * buttons.size() * BUTTON_WIDTH;
            recoverSwipedItem();
        }

        @Override
        public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
            return swipeThreshold;
        }

        @Override
        public float getSwipeEscapeVelocity(float defaultValue) {
            return 0.1f * defaultValue;
        }

        @Override
        public float getSwipeVelocityThreshold(float defaultValue) {
            return 5.0f * defaultValue;
        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            int pos = viewHolder.getAdapterPosition();
            float translationX = dX;
            View itemView = viewHolder.itemView;

            if (pos < 0){
                swipedPos = pos;
                return;
            }

            if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
                if(dX < 0) {
                    List<UnderlayButton> buffer = new ArrayList<>();

                    if (!buttonsBuffer.containsKey(pos)){
                        instantiateUnderlayButton(viewHolder, buffer);
                        buttonsBuffer.put(pos, buffer);
                    }
                    else {
                        buffer = buttonsBuffer.get(pos);
                    }

                    translationX = dX * buffer.size() * BUTTON_WIDTH / itemView.getWidth();
                    drawButtons(c, itemView, buffer, pos, translationX);
                }
            }

            super.onChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
        }

        private synchronized void recoverSwipedItem(){
            while (!recoverQueue.isEmpty()){
                int pos = recoverQueue.poll();
                if (pos > -1) {
                    recyclerView.getAdapter().notifyItemChanged(pos);
                }
            }
        }

        private void drawButtons(Canvas c, View itemView, List<UnderlayButton> buffer, int pos, float dX){
            float right = itemView.getRight();
            float dButtonWidth = (-1) * dX / buffer.size();

            for (UnderlayButton button : buffer) {
                float left = right - dButtonWidth;
                button.onDraw(
                        c,
                        new RectF(
                                left,
                                itemView.getTop(),
                                right,
                                itemView.getBottom()
                        ),
                        pos
                );

                right = left;
            }
        }

        public void attachSwipe(){
            ItemTouchHelper itemTouchHelper = new ItemTouchHelper(this);
            itemTouchHelper.attachToRecyclerView(recyclerView);
        }

        public abstract void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons);

        public static class UnderlayButton {
            private String text;
            private int imageResId;
            private int color;
            private int pos;
            private RectF clickRegion;
            private UnderlayButtonClickListener clickListener;

            public UnderlayButton(String text, int imageResId, int color, UnderlayButtonClickListener clickListener) {
                this.text = text;
                this.imageResId = imageResId;
                this.color = color;
                this.clickListener = clickListener;
            }

            public boolean onClick(float x, float y){
                if (clickRegion != null && clickRegion.contains(x, y)){
                    clickListener.onClick(pos);
                    return true;
                }

                return false;
            }

            public void onDraw(Canvas c, RectF rect, int pos){
                Paint p = new Paint();

                // Draw background
                p.setColor(color);
                c.drawRect(rect, p);

                // Draw Text
                p.setColor(Color.WHITE);
                p.setTextSize(LayoutHelper.getPx(MyApplication.getAppContext(), 12));

                Rect r = new Rect();
                float cHeight = rect.height();
                float cWidth = rect.width();
                p.setTextAlign(Paint.Align.LEFT);
                p.getTextBounds(text, 0, text.length(), r);
                float x = cWidth / 2f - r.width() / 2f - r.left;
                float y = cHeight / 2f + r.height() / 2f - r.bottom;
                c.drawText(text, rect.left + x, rect.top + y, p);

                clickRegion = rect;
                this.pos = pos;
            }
        }

        public interface UnderlayButtonClickListener {
            void onClick(int pos);
        }
    }


Usage:----------------


SwipeHelper swipeHelper = new SwipeHelper(this, recyclerView) {
    @Override
    public void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons) {
        underlayButtons.add(new SwipeHelper.UnderlayButton(
                "Delete",
                0,
                Color.parseColor("#FF3C30"),
                new SwipeHelper.UnderlayButtonClickListener() {
                    @Override
                    public void onClick(int pos) {
                        // TODO: onDelete
                    }
                }
        ));

        underlayButtons.add(new SwipeHelper.UnderlayButton(
                "Transfer",
                0,
                Color.parseColor("#FF9502"),
                new SwipeHelper.UnderlayButtonClickListener() {
                    @Override
                    public void onClick(int pos) {
                        // TODO: OnTransfer
                    }
                }
        ));
        underlayButtons.add(new SwipeHelper.UnderlayButton(
                "Unshare",
                0,
                Color.parseColor("#C7C7CB"),
                new SwipeHelper.UnderlayButtonClickListener() {
                    @Override
                    public void onClick(int pos) {
                        // TODO: OnUnshare
                    }
                }
        ));
    }
};
 类似资料:
  • 我已经从sqlite中填充了RecolyerView。当单击每一行时,row将从sqlite中删除,但删除后RecolyerView不显示更新的列表。回收器视图仅在再次启动活动后显示更新的列表。我的问题是,在没有刷新的情况下,从recylcerview中删除一个项目后,如何很快更新回收器视图。 下面是我的代码 SecondActivity.java DatabaseHelpher.java Dat

  • 在适配器中 我试过了所有的方法,但是很难从RecolyerView中滑动项目,并且当snackbar的undo被按下时,我希望该项目重新出现。我希望从RecolyerView中滑动项目,并且当项目被滑动时,底部的项目应该向上移动。

  • 在我的应用程序中,我在回收商视图中显示项目列表。我为回收商视图中的每个项目创建了两个功能编辑和删除。使用此应用程序,用户可以创建任务列表,可以编辑项目,也可以从回收器视图中删除项目。现在,如果我单击“编辑”,它就可以完美地工作。但是,如果我单击删除选项,则应用程序崩溃,并且消息数组索引在adaper类中因rance异常而崩溃。 这是我的适配器代码。我还提到了 代码中的行 ,其中我遇到了应用程序崩溃

  • 我正在用AppWidgetHostViews填充RecyclerView。它们被排序一个比一个低,每个都有删除按钮旁边。这就是我如何设置RecyclerView和适配器(Event.Object是AppWidgetHostView): 这是保存AppWidgetHostViews的适配器: 因此它再次为适配器设置数据并通知数据集已更改。 但问题是,当我单击“删除”按钮时,项目没有被正确删除。Vie

  • 我想使用swipe手势(即gmail应用程序)实现recyclerview项目之间的导航。这样,用户就不必返回列表,只需单击下一个项目就可以获得其详细信息视图。我找不到如何实现这一点的教程。