I am trying to port some iOS functionality to Android.
I intent to create a table where on swipe to the left shows 2 button: Edit and Delete.
I have been playing with it and I know I am very close. The secret really lies on the method OnChildDraw.
I would like to Draw a Rect that fits the text Delete then draw the Edit text besides it with their respective background color. The remaining white space when clicked should restore the row to its initial position.
I have managed to paint the background while the user is swiping to the sides but I don't know how to add the listeners and once it is swiped to the side, the dragging function begins to misbehave.
I am working on Xamarin but pure java solutions also are accepted as I can easily port them to c#.
public class SavedPlacesItemTouchHelper : ItemTouchHelper.SimpleCallback
{
private SavedPlacesRecyclerviewAdapter adapter;
private Paint paint = new Paint();
private Context context;
public SavedPlacesItemTouchHelper(Context context, SavedPlacesRecyclerviewAdapter adapter) : base(ItemTouchHelper.ActionStateIdle, ItemTouchHelper.Left)
{
this.context = context;
this.adapter = adapter;
}
public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
{
return false;
}
public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
{
}
public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
{
float translationX = dX;
View itemView = viewHolder.ItemView;
float height = (float)itemView.Bottom - (float)itemView.Top;
if (actionState == ItemTouchHelper.ActionStateSwipe && dX <= 0) // Swiping Left
{
translationX = -Math.Min(-dX, height * 2);
paint.Color = Color.Red;
RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
c.DrawRect(background, paint);
//viewHolder.ItemView.TranslationX = translationX;
}
else if (actionState == ItemTouchHelper.ActionStateSwipe && dX > 0) // Swiping Right
{
translationX = Math.Min(dX, height * 2);
paint.Color = Color.Red;
RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
c.DrawRect(background, paint);
}
base.OnChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
}
}
}
This is what I currently have.
If you know how to add listeners or any suggestions please leave a comment!
UPDATE:
I just realized that on double tap on the white remaining space of the row already restore the row to its initial state. Not a single tap though :(
from RecyclerView ItemTouchHelper Buttons on Swipe
No comments:
Post a Comment