Navaneeth
Navaneeth

Reputation: 122

Detecting touch on both child and parent simultaneously without override methods

I have a parent ViewGroup and a View added as its child. This setup resembles my original application where I have an image. If I pinched on the image, its parent should handle the pinch. I need to detect tap on the image as well.

I have added gesture detectors on both the parent and child views. I don’t have access to the classes of these views, so I cannot modify the class by overriding methods such as DispatchTouchEvent, OnInterceptTouchEvent.

So, I am using the Touch event of the views. In the event handler, I am calling the gesture detectors’ OnTouchEvent with the MotionEvent parameter.

The problem is that when I touch or pinch on the child, only the Touch event of the child is fired. The child fully consumes the touch. Because of this, the parent’s Touch event is never fired, and it is impossible to detect any gestures on the parent. Please note that the child is of the same size as the parent, so it entirely covers the parent.

Below is the simplified code sufficient to reproduce the problem.

public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        FrameLayout activityMainLayout = FindViewById<FrameLayout>(Resource.Id.frameLayoutContainer);

        ParentView parentView = new ParentView(this);
        parentView.Touch += ParentView_Touch;
        parentView.LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent);
        activityMainLayout.AddView(parentView);
        
        ChildView childView = new ChildView(this);
        childView.Touch += ChildView_Touch;
        parentView.AddView(childView);
    }

    private void ChildView_Touch(object sender, View.TouchEventArgs e)
    {
        //gestureDetector.OnTouchEvent(e.Event);
    }

    private void ParentView_Touch(object sender, View.TouchEventArgs e)
    {
        //gestureDetector.OnTouchEvent(e.Event);
    }
}

internal class ParentView : ViewGroup
{
    public ParentView(Context context) : base(context)
    {
        SetBackgroundColor(Color.Yellow);
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        var child = GetChildAt(0);
        child.Layout(0,0,r-l, b-t);
    }
}

internal class ChildView : View
{
    public ChildView(Context context) : base(context)
    {
        SetBackgroundColor(Color.Red);
    }
}

I want to detect the full touch cycle on both the views. How can I make the Touch event for both the child and the parent be fired, when the user touches on the child so that I can detect any gesture on both views?

Upvotes: 2

Views: 379

Answers (0)

Related Questions