1.先導入函示庫(build.gradle: Module)
dependencies {
implementation 'me.yuqirong:cardswipelayout:1.0.0'
}
2.程式碼範例
a.創建要展示的View
image_item.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>
b.創建Adapter
ImageAdapter.class
class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageHolder> {
@NonNull
@Override
public ImageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.image_item, parent, false);
return new ImageHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ImageHolder holder, int position) {
holder.imageView.setImageDrawable(getDrawable(list.get(position)));
}
@Override
public int getItemCount() {
return list.size();
}
class ImageHolder extends RecyclerView.ViewHolder {
ImageView imageView;
ImageHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView2);
}
}
}
c.初始化RecyclerView
List<Integer> list = new ArrayList<>();
list.add(R.drawable.i_23);
list.add(R.drawable.i_24);
list.add(R.drawable.i_25);
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.setAdapter(new ImageAdapter());
CardItemTouchHelperCallback cardCallback = new CardItemTouchHelperCallback(recyclerView.getAdapter(), list);
ItemTouchHelper touchHelper = new ItemTouchHelper(cardCallback);
CardLayoutManager cardLayoutManager = new CardLayoutManager(recyclerView, touchHelper);
recyclerView.setLayoutManager(cardLayoutManager);
touchHelper.attachToRecyclerView(recyclerView);
cardCallback.setOnSwipedListener(new OnSwipeListener() {
@Override
public void onSwiping(RecyclerView.ViewHolder viewHolder, float v, int i) {
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, Object o, int i) {
}
@Override
public void onSwipedClear() {
}
});
d.效果展示
左右滑動都可以下一張