Search code examples
androidxamarin.androidandroidxandroid-slider

How to implement Google.Android.Material.Slider ChangeListener or addOnChangeListener events in Xamarin.Android


I added a control Google.Android.Material.Slider and I need to listen when user select a value on it. According to Google's documentation (https://material.io/components/sliders/android#using-sliders) the listeners may be addOnChangeListener or addOnSliderTouchListener but these events aren't available to implement on Xamarin AndroidX Material package.

I'm using the package Xamarin.Google.Android.Material version 1.3.0.1

There's another event that listen and return the selected value when it change or another way to implement it?


Solution

  • You can get his method by reflection, and then listen to it:

    Slider slider = FindViewById<Slider>(Resource.Id.slider1);
    var method = Java.Lang.Class.ForName("com.google.android.material.slider.BaseSlider").GetDeclaredMethods().FirstOrDefault(x => x.Name == "addOnChangeListener");
    method?.Invoke(slider, this); // this is implementing IBaseOnChangeListener
    

    so let your activity implement IBaseOnChangeListener interface:

    public class YourActivity: AppCompatActivity, IBaseOnChangeListener
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            ...
            Slider slider = FindViewById<Slider>(Resource.Id.slider1);
            var method = Java.Lang.Class.ForName("com.google.android.material.slider.BaseSlider").GetDeclaredMethods().FirstOrDefault(x => x.Name == "addOnChangeListener");
            method?.Invoke(slider, this); // this is implementing IBaseOnChangeListener           
        }     
    
        public void OnValueChange(Java.Lang.Object p0, float p1, bool p2)
        {
            Console.WriteLine("slide:" + p1);//p1 is the value you want
        }
    }