可能已经晚了,但仍有帮助。
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_childs, container, false);
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
recyclerView.addItemDecoration(new VerticalItemDecoration());
recyclerView.setAdapter(new ChildCareAdapter());
touchHelper.attachToRecyclerView(recyclerView); // Attaching with RecyclerView
return v;
}
ItemTouchHelper touchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
if (i == ItemTouchHelper.LEFT) {
Toast.makeText(getContext(),"Swipe left",Toast.LENGTH_SHORT).show();
} else if (i == ItemTouchHelper.RIGHT) {
Toast.makeText(getContext(),"Swipe right",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
float alpha = 1 - (Math.abs(dX) / recyclerView.getWidth());
viewHolder.itemView.setAlpha(alpha);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
});
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT){
Log.i("ItemSwipe", "LEFT");
}
else if (direction == ItemTouchHelper.RIGHT){
Log.i("ItemSwipe", "RIGHT");
}
}