Search code examples
androideventsxamarin.androidunsubscribe

this.Touch - Event firing multiple times, don't know how to unsubscribe


This problem should be fairly simple (I think), but I don't know how to do it correctly. I am still very new to programming.

I have a simple class that inherits from EditText. There are 2 problems:

  1. Initially, the Touch event fires 3 times, the second touch will fire the event 5 times and so on. What is going on here?
  2. I don't know how to unsubscribe the event, or a at what stage. Normally, when working with an activity, I simply subscribe during OnResume and unsubscribe during OnPause. What is the right solution in this case? Should I write a custom method and call that from a parent class? Should I implement IDisposable or something similar? Should I write the class in a different way?

This is my custom edit text demo class:

    namespace HelloWorld_Android {
        class DemoEditText : EditText {
            public DemoEditText (Context context, IAttributeSet attrs) : base(context, attrs) {
                this.Touch += HandleTouch;
            }

            void HandleTouch (object sender, TouchEventArgs e) {
                Console.WriteLine ("Fired");
            }
        }
    }

The activity:

    namespace HelloWorld_Android {
        [Activity (Label = "HelloWorld_Android", MainLauncher = true)]
        public class MainActivity : Activity {
            protected override void OnCreate (Bundle bundle) {
                base.OnCreate (bundle);
                SetContentView(Resource.Layout.Main);
            }
        }
    }

My XML:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <HelloWorld_Android.DemoEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/test"
         />
    </LinearLayout>

Solution

  • This problem is fixed, however no code has been changed. I think this was due to some kind of bug within xamarin.android 4.12, as of now I am using Xamarin.Android 4.12.6. I had other (unrelated) problems with WebConnectionStream.WriteRequestAsync (fixed in 4.12.6) as well, maybe something else went wrong which caused a memory leak (not removing touch delegate) or something, not sure.