How to make a Floating Action Button in Xamarin Fo

2020-06-13 05:42发布

I'm building a Xamarin CrossPlatform App!

I wanted to add a floating action button at the bottom right corner of the app page just like this

https://i.stack.imgur.com/4PJcv.jpg

Here is my XAML code:

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.Views.HomePage">


    <ListView x:Name="Demolist" ItemSelected="OnItemSelected" BackgroundColor="AliceBlue">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.ContextActions>
                        <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"
                                 Text="More" />
                        <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}"
                                 Text="Delete" IsDestructive="True" />
                    </ViewCell.ContextActions>
                    <StackLayout>

                        <StackLayout Padding="15,0">
                            <Label Text="{Binding employee_name}" FontAttributes="bold" x:Name="en"/>
                            <Label Text="{Binding employee_age}"/>
                        </StackLayout>

                    </StackLayout>

                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>



</ContentPage>

How can I do this using XAML? Help me through this, Thanks!

5条回答
闹够了就滚
2楼-- · 2020-06-13 06:15

the quickest way:

  1. Install this Nuget: https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android
  2. Position the Floating Action Button (FAB) Like this:
      <?xml version="1.0" encoding="utf-8" ?>
        <ContentPage
            x:Class="Tawsil.Views.DemoPage"
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:fab="clr-namespace:Refractored.FabControl;assembly=Refractored.FabControl">

            <AbsoluteLayout>
                <Grid AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All">

                    <!-- your content here -->

                </Grid>

                <!-- the FAB -->
                <fab:FloatingActionButtonView AbsoluteLayout.LayoutBounds="1, 1, AutoSize, AutoSize" AbsoluteLayout.LayoutFlags="PositionProportional" ImageName="add.png" />
            </AbsoluteLayout>
        </ContentPage>

Don't forget to add the "add.png" icon to your resources

查看更多
淡お忘
3楼-- · 2020-06-13 06:24

**

If you want a solution thats simple and without downloading libraries or anything try this:

**

In your xaml you can use a normal button with rounded corners. Just make sure both width and height are the same. To have it float use a absolute layout and put the button on the bottom. I pasted mine and its style entry from my app.xml resource dictionary.

(Ive used both the james montenago packages and the suave controls. The first doesn't work on iOS and the latter doesn't show images on Android. This solution works on both iOS and Android.)

XAML:

<AbsoluteLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<!-- other content goes here -->      
  <Button x:Name="yourname" Image="baseline_menu_white_24"
                Clicked="OnFabMenuClick" IsVisible="True"
                AbsoluteLayout.LayoutFlags="PositionProportional"
                AbsoluteLayout.LayoutBounds="1, 1, AutoSize, AutoSize"
                Style="{StaticResource FABPrimary}"  />
            </AbsoluteLayout>

Resource dictionary entry:

<Color x:Key="DarkButtonBackground">#921813</Color> 
            <Style x:Key="FABPrimary" TargetType="Button">
                <Setter Property="CornerRadius" Value="100"/>
                <Setter Property="BackgroundColor" Value="{StaticResource DarkButtonBackground}"/>
                <Setter Property="HeightRequest" Value="55"/>
                <Setter Property="WidthRequest" Value="55"/>
                <Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
                <Setter Property="VerticalOptions" Value="CenterAndExpand"/>
                <Setter Property="Padding" Value="15"/>
                <Setter Property="Margin" Value="0,0,0,15"/>
            </Style>
  • You can ignore the resource dictionary entry if you want and instead put the properties directly in the button declaration in your xaml file.
  • I have found that on some iOS devices, the buttons do not display correctly if the radius is set to 100. This can be fixed to setting the CornerRadius to half of the width and height, or you can use OnPlatform like this:
     <Setter Property="CornerRadius">
          <OnPlatform iOS="25" Android="100"/>
     </Setter>

(When height and width are both 50.)

查看更多
Rolldiameter
4楼-- · 2020-06-13 06:27

You can use for Android, Floating Action Button (https://developer.android.com/guide/topics/ui/floating-action-button) if you want to use native control, and a custom board for iOS. Otherwise you can add to your Xamarin.Forms page a RelativeLayout container and specity constraints where you want. Something like this:

 <ContentPage.Content>
    <RelativeLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <StackLayout >
            <Label Text="YOUR CODE" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
        </StackLayout>
        <Button CornerRadius="25" Text="B"
                 RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,
        Property=Width, Factor=1, Constant=-60}"
                 RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,
        Property=Height, Factor=1, Constant=-60}" />
    </RelativeLayout>
</ContentPage.Content>

You can change Button with any other control and you can correct position just changing the value of "Constant=-60"

查看更多
乱世女痞
5楼-- · 2020-06-13 06:32

You can use an ImageButton (Xamarin.Forms v3.4+)

Create your image with a transparent background in your favorite editor and then assign it a location on the Page.

enter image description here

Example using an AbsoluteLayout, just place your "FAB" as the last element so that its Z-order is highest and it will "float" above the rest of the content.

    <AbsoluteLayout>

         ~~~~

        <ImageButton Source="editFAB.png" 
            BackgroundColor="Transparent"
            AbsoluteLayout.LayoutFlags="PositionProportional"  
            AbsoluteLayout.LayoutBounds=".95,.95,80,80" 
            Clicked="Handle_Clicked" />
    </AbsoluteLayout>

Output:

enter image description here

查看更多
叼着烟拽天下
6楼-- · 2020-06-13 06:37

Using Floating action button in Xamarin Forms is easier than you might think, All you need is a little bit of AbsoluteLayout and an ImageButton that can respond to your clicks and voila! your FAB is ready

Add a custom ImageButton Control something like below:

public class ImageButton : Image
{
    public static readonly BindableProperty CommandProperty =
        BindableProperty.Create("Command", typeof(ICommand), typeof(ImageButton), null);

    public static readonly BindableProperty CommandParameterProperty =
        BindableProperty.Create("CommandParameter", typeof(object), typeof(ImageButton), null);

    public event EventHandler ItemTapped = (e, a) => { };

    public ImageButton()
    {
        Initialize();
    }

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public object CommandParameter
    {
        get { return GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }

    private ICommand TransitionCommand
    {
        get
        {
            return new Command(async () =>
            {
                AnchorX = 0.48;
                AnchorY = 0.48;
                await this.ScaleTo(0.8, 50, Easing.Linear);
                await Task.Delay(100);
                await this.ScaleTo(1, 50, Easing.Linear);
                Command?.Execute(CommandParameter);

                ItemTapped(this, EventArgs.Empty);
            });
        }
    }

    public void Initialize()
    {
        GestureRecognizers.Add(new TapGestureRecognizer
        {
            Command = TransitionCommand
        });
    }
}

Once you have that up and running in a layout whose parent-most is an AbsoluteLayout add the ImageButton like below:

  <customControls:ImageButton Source="{Binding ImageSource}"
                                    Command="{Binding AddCommand}"                                        AbsoluteLayout.LayoutFlags="PositionProportional"                                        AbsoluteLayout.LayoutBounds="1.0,1.0,-1,-1"
                                    Margin="10" />

Where customControls is the namespace where you added your ImageButton custom control.

For better understanding check where I referenced it from which can be found here

Good luck

Revert in case you have any sort of query.

查看更多
登录 后发表回答