How to trigger context actions with custom event?

CloudCherryCloudCherry SGMember
edited August 2015 in Xamarin.Forms

Hi all,
I'm trying to implement a Listview, where user have to select one or more rows and delete. So my question is can I use context actions to show up when they select a row instead of long tap (i.e. single tab on row). Can I do this?? Is it achievable with xamarin.forms?

Thanks in Advance

Answers

  • @CloudCherry did you find a solution? I have the same problem!

  • We are using a listview inside a carousel view, and found, on Android, the long tap would often get confused as the start of a swipe if the user's finger wasn't perfectly still.
    We did the following to bring up the ContextActions, on Android, via a double tap on a cell. The long tap still works, but users find the double tap much simpler.

    Step 1 - add a TapGestureRecogniser to your viewcell with NumberOfTaps set to 2. Do not specify a command.
    Step 2 - use this custom renderer on Android:

    public class DoubleTapContextActionViewCellRenderer : ViewCellRenderer
    {
        protected override View GetCellCore(Cell item, View convertView, ViewGroup parent, Context context)
        {
            var view = base.GetCellCore(item, convertView, parent, context);
    
            // look for a double tap gesture recogniser on the cell
            // It would be nice to have a dedicated class, derived from TapGestureRecogniser, but it is a sealed class.
            var customRecogniser = (item as ViewCell)?.View?.GestureRecognizers?.SingleOrDefault(gr => (gr as TapGestureRecognizer)?.NumberOfTapsRequired == 2) as TapGestureRecognizer;
            if (customRecogniser == null)
                return view;
    
            // setup the command on the double tap gesture recogniser to trigger the context action
            // set the command every time, in case the underlying Android View is re-used for a different Xamarin.Forms cell
            customRecogniser.Command = new Command(() =>
            {
                TriggerContextAction(parent as Android.Widget.ListView, view);
            });
    
            return view;
        }
    
        private static void TriggerContextAction(Android.Widget.ListView listView, View view)
        {
            var position = listView.GetPositionForView(view);
    
            var adapter = (listView.Adapter as HeaderViewListAdapter)?.WrappedAdapter as CellAdapter;
            if (adapter == null)
                return;
    
            // the only way to trigger the ContextAction UI is to make the adapter think a long press has happened
            adapter.OnItemLongClick(listView, view, position, view.Id);
        }
    }
    
Sign In or Register to comment.