How to add swipe functionality on Android CardView?

你离开我真会死。 提交于 2019-11-28 05:34:35
Konstantin Loginov

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(...);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!