Sunday, April 3, 2016

Floating Action Button in Xamarin Forms

I'm loving experimenting with Xamarin Forms at the moment. So when I wanted to include a Floating Action Button (FAB) in Android versions of a Forms App, I naturally wanted to try to get this working with Forms first.  I realise you can use Xamarin Native Android views in a Forms App, but I enjoy XAML and creating reusable controls.

My first port of call was James Montemagno's GitHub and blog and found his examples for a FAB.

https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android
He does mention he ported this code from: https://github.com/makovkastar/FloatingActionButton

This looks perfect, but I wanted to improve the Forms example to be mostly XAML based and try to best encapsulate the events into the FAB control to minimise the amount of work the consuming developer has to do.

Here's my code so far.
https://github.com/Benrnz/XamlFloatingActionButton

Its far from perfect, but works great.  Be aware however, that if your ObservableCollection has duplicate values in it, the FAB will exhibit unexpected hide/show behaviour.

Here's what I ended up with in my XAML:

  <AbsoluteLayout VerticalOptions="FillAndExpand"  
           HorizontalOptions="FillAndExpand">  
     <StackLayout AbsoluteLayout.LayoutFlags="All"  
            AbsoluteLayout.LayoutBounds="0,0,1,1">  
       <Label Text="FAB Test 1"  
           VerticalOptions="Center"  
           HorizontalOptions="Center" />  
       <ListView x:Name="MainList"   
            ItemsSource="{Binding MyItems}"  
            VerticalOptions="FillAndExpand"/>  
     </StackLayout>  
     <fabTest1:FloatingActionButtonView x:Name="Fab"   
                       AbsoluteLayout.LayoutFlags="PositionProportional"   
                       AbsoluteLayout.LayoutBounds="1,1,AutoSize,AutoSize"  
                       ImageName="ic_add.png"  
                       ColorNormal="#ff3498db"  
                       ColorPressed="Black"  
                       ColorRipple="#ff3498db"  
                       Command="{Binding FabExecuteCommand}"  
                       ParentList="{Binding Source={x:Reference MainList}, Path=.}"/>  
   </AbsoluteLayout>  

No comments:

Post a Comment