androidmobilexamarin.androidmvvmcross

Update the Alpha of TextView in MVVMCross in C#


I am having an MVVMCross app in which I want to update the Alpha value when user selects some value more than expected one.

I have textview and below is the code.

    <TextView
    style="@style/B1.TextView"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:background="@drawable/shape_circle_bluescale1"
    android:gravity="center"
    android:text="@string/plus"
    android:textColor="@color/bluescale4"
    app:MvxBind="Click IncrementQuantityCommand; Alpha QtyAlpha;"/>

I have a public float QtyAlpha in my view model and I want to update on runtime on below method but it is not getting updated. Method is called but value is not updated in Android UI.

View Model method to update the Alpha of TextView.

    public void SetQuantityCount(int qty, float alpha = 1.0f)
    {
        Qty = qty.ToString();
        QtyAlpha = alpha;
    }

It is getting updated in iOS UI.

Which bind value am I doing wrong?


Solution

  • May MvvmCross did not have built-in support for directly binding the Alpha property of a TextView. You will need to create a custom binding for this purpose.

    Create a Custom Binding:

    public class AlphaTextViewTargetBinding : MvxAndroidTargetBinding<TextView, int>
    {
        public BackgroundViewTargetBinding(TextView view) : base(view)
        {
        }
    
        // Alpha from 0 to 255
        protected override void SetValueImpl(TextView target, int value)
        {
            target.Alpha = value;
        }
    
        public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;
    }
    

    Register the Custom Binding (Setup.cs)

    protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
    {
                base.FillTargetFactories(registry);
    
                registry.RegisterFactory(new MvxCustomBindingFactory<TextView>("Alpha",
                    view => new AlphaTextViewTargetBinding(view)));
    }
    

    Use the Custom Binding in XML:

    <TextView
        style="@style/B1.TextView"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:background="@drawable/shape_circle_bluescale1"
        android:gravity="center"
        android:text="@string/plus"
        android:textColor="@color/bluescale4"
        app:MvxBind="Click IncrementQuantityCommand; Alpha QtyAlpha;"/>
    

    I am currently using MvvmCross version 8.0.2 for demonstration purposes. Please note that the override method may vary depending on the version being used.

    Hope it helps!