RecyclerView ItemTouchHelper Buttons on Swipe

后端 未结 11 1271
春和景丽
春和景丽 2020-11-27 11:05

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

11条回答
  •  遥遥无期
    2020-11-27 11:32

    I wanted to use this touch gesture in my app too, after working too much with Itemtouchhelper I decided to write my own touch handler:

        private class TouchHelper : Java.Lang.Object, View.IOnTouchListener
        {
            ViewHolder vh;
            public TouchHelper(ViewHolder vh)
            { this.vh = vh;  }
    
            float DownX, DownY; bool isSliding;
            TimeSpan tsDown;
            public bool OnTouch(View v, MotionEvent e)
            {
                switch (e.Action)
                {
                    case MotionEventActions.Down:
                        DownX = e.GetX(); DownY = e.GetY();
                        tsDown = TimeSpan.Now;
                        break;
                    case MotionEventActions.Move:
                        float deltaX = e.GetX() - DownX, deltaY = e.GetX() - DownY;
                        if (Math.Abs(deltaX) >= Values.ScreenWidth / 20 || Math.Abs(deltaY) >= Values.ScreenWidth / 20)
                            isSliding = Math.Abs(deltaX) > Math.Abs(deltaY);
    
                        //TextsPlace is the layout that moves with touch
                        if(isSliding)
                            vh.TextsPlace.TranslationX = deltaX / 2;
    
                        break;
                    case MotionEventActions.Cancel:
                    case MotionEventActions.Up:
                        //handle if touch was for clicking
                        if (Math.Abs(deltaX) <= 50 && (TimeSpan.Now - tsDown).TotalMilliseconds <= 400)
                            vh.OnTextsPlaceClick(vh.TextsPlace, null);
                        break;
                }
                return true;
            }
        }
    

    Note: Set this as ontouchlistener of your viewholder content when creating the viewholder. You can add your animations to return the item to its first place.

    You can also write your custom layoutmanager to block vertical scroll while item is sliding.

提交回复
热议问题