Search code examples
androidxamarindata-bindingxamarin.androidmvvmcross

MvvmCross Xamarin.Android FloatingActionButton toggle visibility


This is my FloatingActionButton:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_retailer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:tint="@android:color/white"
        app:backgroundTint="@color/colorPrimary"
        app:srcCompat="@drawable/ic_add_black_24dp"
        local:MvxBind="Visibility IsAddButtonVisible, Converter=Visibility" />

Its visibility property is bound via MvvmCross to IsAddButtonVisible:

private bool _isAddButtonVisible = true;
public bool IsAddButtonVisible
{
    get
    {
        return _isAddButtonVisible;
    }
    set
    {
        _isAddButtonVisible = value;
        RaisePropertyChanged(() => IsAddButtonVisible);
    }
}

When I change the boolean value

ViewModel.IsAddButtonVisible = false;

...nothing happens. What am I doing wrong here? Thanks in advance!

Edit: when I bind using Visible, the toggling works

local:MvxBind="Visible IsAddButtonVisible"

but now I can't see any hide/show animations on the FloatingActionButton...


Solution

  • You would have to make use of a custom binding to use the method calls instead of the Visibility ViewStates changes.


    Create the target binding that handles the executing the show and hide method calls based on the bool value you bind to.

    public class FloatingActionButtonAnimateVisibleTargetBinding
        : MvxAndroidTargetBinding
    {
        protected FloatingActionButton View => (FloatingActionButton)Target;
    
        public FloatingActionButtonAnimateVisibleTargetBinding(FloatingActionButton target)
            : base(target)
        {
        }
    
        public override Type TargetType => typeof(bool);
    
        protected override void SetValueImpl(object target, object value)
        {
            var isVisible = value.ConvertToBoolean();
            var floatingActionButton = target as FloatingActionButton;
    
            if (isVisible)
                floatingActionButton.Show();
            else
                floatingActionButton.Hide();
        }
    

    }

    Register the custom binding in your platform Setup.cs

    protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
    {
        base.FillTargetFactories(registry);
    
        registry.RegisterCustomBindingFactory<FloatingActionButton>(
            "VisibleAnim",
            button => new FloatingActionButtonAnimateVisibleTargetBinding(button));
    }
    

    Then you should be able to make use of the binding in your XML

    local:MvxBind="VisibleAnim IsAddButtonVisible"