How to add swipe functionality on Android CardView?

后端 未结 1 1870
轮回少年
轮回少年 2020-12-08 05:39

I have a single CardView that contains two TextViews and two ImageViews. I want to be able to swipe left and right to \"dismiss\". I actually want swipe right to send an Int

相关标签:
1条回答
  • 2020-12-08 06:34

    You'll have to put it inside RecyclerView (and your CardView as the only item there)

    Then, use ItemTouchHelper.SimpleCallback to itemTouchHelper.attachToRecyclerView(recyclerView);

    It will give you animations and in

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
    }
    

    you can specify particular action based on the swipe direction.

    See full instruction here: Swipe to Dismiss for RecyclerView

    Also, you'll have to disable vertical scroll in RecyclerView:

    public class UnscrollableLinearLayoutManager extends LinearLayoutManager {
        public UnscrollableLinearLayoutManager(Context context) {
            super(context);
        }
    
        @Override
        public boolean canScrollVertically() {
            return false;
        }
    }
    
    .....
    
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new UnscrollableLinearLayoutManager(this));
    recyclerView.setAdapter(new RestaurantCardAdapter());
    

    Otherwise - once you'll try to scroll up or down - you'd see RecyclerView's end-of-list animations.

    Upd:

    Here's RecyclerView.Adapter I used for test:

    private class RestaurantCardAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new RestaurantViewHolder(new RestaurantCard(parent.getContext()));
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {}
    
        @Override
        public int getItemCount() {
            return 1;
        }
    
        private class RestaurantViewHolder extends RecyclerView.ViewHolder {
            public RestaurantViewHolder(View itemView) {
                super(itemView);
            }
        }
    }
    

    RestaurantCard - is just a custom View (extends CardView in our case):

    public class RestaurantCard extends CardView {
        public RestaurantCard(Context context) {
            super(context);
            initialize(context);
        }
    
        public RestaurantCard(Context context, AttributeSet attrs) {
            super(context, attrs);
            initialize(context);
        }
    
        private void initialize(Context context){
            LayoutInflater.from(context).inflate(R.layout.card, this);
            // ImageView imageView = (ImageView)getView.findViewById(...);
        }
    }
    
    0 讨论(0)
提交回复
热议问题