Android drag elevation translationz on cardview with itemTouchHelper in Recyclerview - android

i have a problem figuring out how to give cardViews temporarily elevation on drag. I use a recycler view with cardViews and this is my itemtouchhelper:
class ListTouchHelper extends ItemTouchHelper.Callback {
private final ActionCompletionContract contract;
public ListTouchHelper(ActionCompletionContract contract) {
this.contract = contract;
}
#Override
public int getMovementFlags(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
contract.onViewMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
if (direction == ItemTouchHelper.LEFT) {
contract.onViewSwipedLeft(viewHolder.getAdapterPosition());
} else if (direction == ItemTouchHelper.RIGHT) {
contract.onViewSwipedRight(viewHolder.getAdapterPosition());
}
}
public interface ActionCompletionContract {
void onViewMoved(int oldPosition, int newPosition);
void onViewSwipedLeft(int position);
void onViewSwipedRight(int position);
}
}
I have managed to give it temporarily elevation with:
Which resulted in: (the shadows are somehow clipped?)
However, once the view is just slightly moved, the elevation disappears:
My question is: how do i get the elevation (including shadows) when the cards are being dragged?
Thanks in advance!

#LivinTheNoobLife in your solution you are using the ViewPropertyAnimator, but you are not setting any translation to it, hence, no animations will be applied.
This is my solution with a properly working floating animation:
class DragHelper extends ItemTouchHelper.Callback {
private boolean cardPicked = true;
private boolean reset = false;
#Override
public void onChildDraw(#NonNull Canvas c, #NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
// elevate only when picked for the first time
if (cardPicked) {
ViewPropertyAnimator animator = viewHolder.itemView.animate();
animator.translationZ(16);
animator.setDuration(200);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.start();
cardPicked = false;
}
// when your item is not floating anymore
if (reset){
ViewPropertyAnimator animator = viewHolder.itemView.animate();
animator.translationZ(0);
animator.setDuration(200);
animator.setInterpolator(new AccelerateInterpolator());
animator.start();
cardPicked = true;
reset = false;
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
// As the doc says
// Called by the ItemTouchHelper when the user interaction with an element is over and it also completed its animation.
#Override
public void clearView(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
// interaction is over, time to reset our elevation
reset = true;
}
}

Ok so I solved it, kindof. I think for some other reason its not working by default, however I managed to write a workaround.
private boolean first = true; //first draw of cardView?
private boolean last = false; //last draw of cardView?
#Override
public void onChildDraw(#NonNull Canvas c, #NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
//add elevation on first draw
if (first) {
ViewPropertyAnimator animator = viewHolder.itemView.animate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //consider SDK version
viewHolder.itemView.setTranslationZ(7);
animator.start();
}
first = false;
}
//remove translationZ in last edit
if (last) {
ViewPropertyAnimator animator = viewHolder.itemView.animate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //consider SDK version
viewHolder.itemView.setTranslationZ(0);
animator.start();
}
//reset values
last=false;
first=true;
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
#Override
public void clearView(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
last = true; //only one more OnChildDrawWillBeCalled
}
The above code is added to your ItemTouchHelper.Callback and all should work.
The basic idea is to manually control the drawing of the translationz.
For that I figure out when is the first canvas drawn, and when the last, whereas the cancas will show the shadow.
Maxbe one more comment: the ViewPropertyAnimator in combination with the xml layout file is incredibly unintuitive and buggy, so if you can avoided I would reccomend to do so, and instead try programmatically animating the view changes and effects.
Hope this can help someone.

Related

RecyclerView swiping to delete in Fragment?

I'm trying to create a feature where if the user swipes LEFT on an item in the RecyclerView, the item will be deleted.
My RecyclerView is inside a Fragment which is inside a FrameLayout controlled by a BottomNavigation.
I have the code where it works when the RecyclerView is in its own Activity but when I transfer it into a Fragment, the swiping functionality breaks. I'm unable to swipe at all.
In my Fragment, I'm extending the RecyclerItemTouchHelperListener interface.
interface RecyclerItemTouchHelperListener {
void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position);
}
Then I create a Callback
ItemTouchHelper.SimpleCallback ItemTouchHelperCallbackLeft = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT, this);
new ItemTouchHelper(ItemTouchHelperCallbackLeft).attachToRecyclerView(recyclerView);
Now I create a function called OnSwiped to handle the swiping.
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
if (viewHolder instanceof ListAdapter.ViewHolder) {
if (direction == ItemTouchHelper.LEFT) {
String cityName = stationList.get(viewHolder.getAdapterPosition()).getData().getCity();
//Create a backup of the deleted item in case user wants to undo delete
Station deletedStation = stationList.get(viewHolder.getAdapterPosition());
int deletedStationIndex = viewHolder.getAdapterPosition();
//Remove the item from RecyclerView
listAdapter.removeItem(deletedStationIndex);
Snackbar snackbar = Snackbar.make(coordinatorLayout, cityName + " removed from list!", Snackbar.LENGTH_LONG);
snackbar.setAction("UNDO", new View.OnClickListener() {
#Override
public void onClick(View view) {
// undo is selected, restore the deleted item
listAdapter.restoreItem(deletedStation, position);
}
});
snackbar.show();
}
}
}
And here is the RecyclerItemTouchHelper class.
public class RecyclerItemTouchHelper extends ItemTouchHelper.SimpleCallback {
private RecyclerItemTouchHelperListener listener;
public RecyclerItemTouchHelper(int dragDirs, int swipeDirs, RecyclerItemTouchHelperListener listener) {
super(dragDirs, swipeDirs);
this.listener = listener;
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
listener.onSwiped(viewHolder, direction, viewHolder.getAdapterPosition());
}
#Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (viewHolder != null) {
final View foregroundView = ((ListAdapter.ViewHolder) viewHolder).listViewForeground;
getDefaultUIUtil().onSelected(foregroundView);
}
}
#Override
public void onChildDrawOver(Canvas canvas, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
final View foregroundView = ((ListAdapter.ViewHolder) viewHolder).listViewForeground;
getDefaultUIUtil().onDrawOver(canvas, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive);
}
#Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
final View foregroundView = ((ListAdapter.ViewHolder) viewHolder).listViewForeground;
getDefaultUIUtil().clearView(foregroundView);
}
#Override
public void onChildDraw(Canvas canvas, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
final View foregroundView = ((ListAdapter.ViewHolder) viewHolder).listViewForeground;
getDefaultUIUtil().onDraw(canvas, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive);
}
#Override
public int convertToAbsoluteDirection(int flags, int layoutDirection) {
return super.convertToAbsoluteDirection(flags, layoutDirection);
}
}
Keep in mind that everything works when the RecyclerView is inside its own Activity, but when I transfer my RecyclerView into a Fragment this swiping function does not work.
I've fixed my issue by moving the Callback after I initialize my RecyclerView.
recyclerView = itemView.findViewById(R.id.recyclerView);
ItemTouchHelper.SimpleCallback ItemTouchHelperCallbackLeft = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT, this);
new ItemTouchHelper(ItemTouchHelperCallbackLeft).attachToRecyclerView(recyclerView);

How to set the swipe threshold to half the screen?

I have a list (recycleView) of names. Some names are short, some are long. I want to delete them on swipe, but I want to make sure the user swipes more than half the distance of the screen (or width of list).
Currently it is going by the length of the individual item.
I know how to swipe on delete. I have tried overrideing getSwipeThreshold but again that uses the size of the item as its base.
Here's code because SO wants code:
RecyclerView recyclerView = findViewById(R.id.edit_list);
final MyRecyclerViewAdapter adapter = new
MyRecyclerViewAdapter(this, qnames);
//set swipe behavior
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false; //do not allow move
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// Row is swiped from recycler view
int position = viewHolder.getAdapterPosition(); //get position which is swipe
qnames.remove(position); //remove from display list
adapter.notifyItemRemoved(viewHolder.getLayoutPosition()); //update the view
}
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
// view the background view
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
#Override
public float getSwipeThreshold( RecyclerView.ViewHolder viewHolder){
return .9f;
}
Here's some pictures.
So how do I set the swipe threshold to half the screen?
You must return 0.5f in getSwipeThreshold. This is default value, so just remove this override from your class&

How to swipe both side left and right in recyclerview in android

I want to swipe recyclerview both side left and right like below image:-
But I can't do I see many library but I find only one side swipe . I want both side swipe how I do that help me to do do this.
Thanks in advance
You can try below given one lib you just have to some modification
https://github.com/daimajia/AndroidSwipeLayout
Thanks!
It maybe late, but could help.
#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);
}
});
You need something like this:
#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");
}
}

Custom swipe ItemTouchHelper

Hi i have add ItemTouchHelper to my listview and i have do MyItemTouchHelper.attachToRecyclerView(myRecyclerView), then i have implements code for swipe to right:
private ItemTouchHelper itemTouchHelperEventi = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
Evento ev = lista_eventi.get(viewHolder.getAdapterPosition());
analizzaEvento = new AnalizzaEvento(ev.getNome_evento());
adapterRecyclerViewEventi.remove(positionForResult);
adapterRecyclerViewEventi.notifyDataSetChanged();
}
});
Now i want to implement swipe code to remove item how gmail, i want that when i swipe to right background row becomes red and at left of row there is label undo and at right of row there is label delete (or confirm) if i click on right i delete item if i click on left return to the previous situation.
Please don't link other library i want to add this festure at my code without using external library, i don't want to rewrite all code only for this feature.
Is it possible?
Here is sample code
ItemTouchHelper.Callback simpleItemTouchCallback=new ItemTouchHelper.Callback() {
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//Unlock the movement of the item
//If you want only left to right unlock that moment only
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags;
if(viewHolder instanceof HeterogenousAdapter.ImageViewHolder)
swipeFlags = ItemTouchHelper.ANIMATION_TYPE_SWIPE_CANCEL ;
else
swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END ;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//when user swiped this method getting call
int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT){
adapter.removeItem(position);
}else {
removeView();
edit_position = position;
alertDialog.setTitle("Edit Country");
if (objectsArrayList.get(position) instanceof UserInfo){
UserInfo userInfo= (UserInfo) objectsArrayList.get(position);
et_country.setText(userInfo.getFirstName());
}else {
String abc= (String) objectsArrayList.get(position);
et_country.setText("ESHVAR");
}
alertDialog.show();
}
}
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
//when swiped started what you wants to do
//Here you can set Red color with icon on it
Bitmap icon;
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
View itemView = viewHolder.itemView;
float height=(float) itemView.getBottom() - (float) itemView.getTop();
float width =height/3;
if (dX > 0){
paint.setColor(Color.parseColor("#388e3c"));
RectF background = new RectF(
(float)itemView.getLeft(),
(float)itemView.getTop(),
dX,
(float)itemView.getBottom());
c.drawRect(background,paint);
icon = BitmapFactory.decodeResource(getResources(),R.drawable.action_search);
RectF icon_dest = new RectF(
(float)itemView.getLeft()+width,
itemView.getTop()+width,
(float)itemView.getLeft()+2*width,
(float)itemView.getBottom() - width);
c.drawBitmap(icon,null,icon_dest,paint);
}else {
paint.setColor(Color.parseColor("#d32f2f"));
RectF background = new RectF(
(float)itemView.getRight()+dX,
(float)itemView.getTop(),
(float)itemView.getRight(),
(float)itemView.getBottom());
c.drawRect(background,paint);
icon =BitmapFactory.decodeResource(getResources(),R.drawable.action_search);
RectF icon_dest=new RectF(
(float)itemView.getRight()-2*width,
(float)itemView.getTop()+width,
(float)itemView.getRight() - width,
(float)itemView.getBottom() - width);
c.drawBitmap(icon,null,icon_dest,paint);
}
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
//Adding Recycle view to Item touch helper
ItemTouchHelper itemTouchHelper=new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);

ItemTouchHelper callback

I have problems understanding which callback method of ItemTouchHelper is called when i swipe a carditem, but i dont finish the swipe and instead turn it back to the normal state.
What i have currently:
#Override
public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
mCardItemAdapter.deleteCard(viewHolder.getAdapterPosition(), mRecyclerView);
}
which removes the item from the adapter.
And:
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
Log.d("dx =",""+dX);
// Can be modified
if(dX < -300) {
View v = viewHolder.itemView;
RelativeLayout mLayout = (RelativeLayout) v.findViewById(R.id.card_item_layout_relative_layout);
mLayout.setBackgroundResource(R.color.red);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
What i want to achieve ? When i swipe, the background turns red, but when i release the swipe before onSwiped is called, the background stays red, but i want it to be white again.
Hope someone can help me out with this.
Add an additional else clause:
if(dx < -300){...} else { mLayout.setBackgroundResource(R.color.white); }

Categories

Resources