Xamarin.Tip – Adding Dynamic Elevation to Your Xamarin.Forms Buttons

Before Reading

In a previous post, I talked about bringing Material Design to your iOS applications in Xamarin.Forms and adding drop shadows to them. You might want to read that here first: Xamarin.Tips – Creating a Material Design Button in iOS

In another post, we learned how to override the Android Button Elevations. We will be doing this in this post in order to set a dynamic elevation. You can read that here: Xamarin.Tips – Overriding Android Button Shadows/Elevation

Now in this post, we will combine these two concepts with a new custom Xamarin.Forms component called MaterialButton that will have a new Elevation property to control the elevation and shadow of the underlying button control.

The source code and an example can be found here: https://github.com/SuavePirate/MaterialButton

Using the existing code

You can of course use the code I wrote and put on GitHub for this. In order to use it, simply:

  1. Clone the repository at  https://github.com/SuavePirate/MaterialButton
  2. Include all 3 `src` projects in your Solution
  3. Reference the Shared project in all Xamarin.Forms and platform projects
  4. Reference the Android project in your Android projects
  5. Reference the iOS project in your iOS projects
  6. Use the control as below (see example projects to demo)

Reference the control in your XAML:

MainPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"              xmlns:local="clr-namespace:MaterialButtonExample"              xmlns:suave="clr-namespace:SuaveControls.MaterialButton.Shared;assembly=SuaveControls.MaterialButton.Shared"              x:Class="MaterialButtonExample.MainPage">

	<suave:MaterialButton x:Name="MyButton"                            BackgroundColor="#03A9F4"                            TextColor="White"                            Text="Click to raise elevation"                            Elevation="1"                            VerticalOptions="Center"                            HorizontalOptions="Center"                           WidthRequest="300"                           Clicked="MyButton_Clicked"/>

</ContentPage>

MainPage.xaml.cs

namespace MaterialButtonExample
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void MyButton_Clicked(object sender, EventArgs e)
        {
            MyButton.Elevation++;
        }
    }
}

In your iOS AppDelegate you’ll also need to call the Initialize method to ensure that the Custom renderer does not get excluded during linking:

AppDelegate.cs

namespace MaterialButtonExample.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            MaterialButtonRenderer.Initialize();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}

Now you can see your results!

Creating Your Own Material Design Button

First things first, let’s create our new Xamarin.Forms control before we implement our custom renderers:

MaterialButton.cs

namespace SuaveControls.MaterialButton.Shared
{
    public class MaterialButton : Button
    {
        public static BindableProperty ElevationProperty = BindableProperty.Create(nameof(Elevation), typeof(float), typeof(MaterialButton), 4.0f);

        public float Elevation
        {
            get
            {
                return (float)GetValue(ElevationProperty);
            }
            set
            {
                SetValue(ElevationProperty, value);
            }
        }
    }
}

Now let’s implement our iOS and Android custom renderers.

iOS:
MaterialButtonRenderer


[assembly: ExportRenderer(typeof(MaterialButton), typeof(MaterialButtonRenderer))]
namespace SuaveControls.MaterialButton.iOS
{
    public class MaterialButtonRenderer : ButtonRenderer
    {
        public static void Initialize()
        {
            // empty, but used for beating the linker
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null)
                return;

        }

        public override void Draw(CGRect rect)
        {
            base.Draw(rect);
            UpdateShadow();
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if(e.PropertyName == "Elevation")
            {
                UpdateShadow();
            }
        }

        private void UpdateShadow()
        {

            var materialButton = (Shared.MaterialButton)Element;

            // Update shadow to match better material design standards of elevation
            Layer.ShadowRadius = materialButton.Elevation;
            Layer.ShadowColor = UIColor.Gray.CGColor;
            Layer.ShadowOffset = new CGSize(2, 2);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromRect(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;

        }
    }
}

Notice how we use the UpdateShadow method to use the Elevation property to set the ShadowRadius of our UIButton's Layer.

It’s important to also make the UpdateShadow call in the OnElementPropertyChanged so that we can dynamically change the Elevation property in our Xamarin.Forms control and see it reflected in the underlying UIButton.

Now let’s do it on Android:

MaterialButtonRenderer

[assembly: ExportRenderer(typeof(MaterialButton), typeof(MaterialButtonRenderer))]
namespace SuaveControls.MaterialButton.Droid
{
    public class MaterialButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
    {
        ///
<summary>
        /// Set up the elevation from load
        /// </summary>

        /// <param name="e"></param>
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement == null)
                return;

            var materialButton = (Shared.MaterialButton)Element;

            // we need to reset the StateListAnimator to override the setting of Elevation on touch down and release.
            Control.StateListAnimator = new Android.Animation.StateListAnimator();

            // set the elevation manually
            ViewCompat.SetElevation(this, materialButton.Elevation);
            ViewCompat.SetElevation(Control, materialButton.Elevation);
        }

        public override void Draw(Canvas canvas)
        {
            var materialButton = (Shared.MaterialButton)Element;
            Control.Elevation = materialButton.Elevation;
            base.Draw(canvas);
        }

        ///
<summary>
        /// Update the elevation when updated from Xamarin.Forms
        /// </summary>

        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if(e.PropertyName == "Elevation")
            {
                var materialButton = (Shared.MaterialButton)Element;
                ViewCompat.SetElevation(this, materialButton.Elevation);
                ViewCompat.SetElevation(Control, materialButton.Elevation);
                UpdateLayout();
            }
        }
    }
}

Just as mentioned in the iOS implementation, we need to make sure that we implement our changes in both the OnElementChanged method as well as the OnElementPropertyChanged event to ensure we are able to update our Elevation with MVVM.

Now we can use our control in our pages!

MainPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"              xmlns:local="clr-namespace:MaterialButtonExample"              xmlns:suave="clr-namespace:SuaveControls.MaterialButton.Shared;assembly=SuaveControls.MaterialButton.Shared"              x:Class="MaterialButtonExample.MainPage">

	<suave:MaterialButton x:Name="MyButton"                            BackgroundColor="#03A9F4"                            TextColor="White"                            Text="Click to raise elevation"                            Elevation="1"                            VerticalOptions="Center"                            HorizontalOptions="Center"                           WidthRequest="300"                           Clicked="MyButton_Clicked"/>

</ContentPage>

MainPage.xaml.cs

namespace MaterialButtonExample
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void MyButton_Clicked(object sender, EventArgs e)
        {
            MyButton.Elevation++;
        }
    }
}

In your iOS AppDelegate you’ll also need to call the Initialize method to ensure that the Custom renderer does not get excluded during linking:

AppDelegate.cs

namespace MaterialButtonExample.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            MaterialButtonRenderer.Initialize();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}

Now you can see your results!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Advertisement

Xamarin.Tip – Binding a Picker to an Enum

So a recent Xamarin.Forms update released the new Bindable Picker, which allows you to bind an IList of objects to the picker (which will be ToString()‘ed). However, I’ve often find myself needing to create a form for a model that has enum properties. Previously, in order to do this, I would have to create a custom List or string from my enum and map it manually, then read from the SelectedItem bound to another string property, then when I need the actual value I’d have to map it back to the enum it “represents”.

It might have looked something like this:

MyViewModel.cs

...
private DogBreed _breedEnum; // this is our enum of: BorderCollie, LabradorRetriever, PitBull, etc.

public List<string> BreedNames
{
    get
    {
        return new List<string> { "Border Collie", "Labrador Retriever", "Pit Bull" };
    }
}

private string _selectedBreed;
public string SelectedBreed
{
    get
    {
        return _selectedBreed;
    }
    set
    {
        Set(ref _selectedBreed, value); // this is using MvvmLight
    }
}

public void DoSomethingWithTheBreed()
{
    switch(SelectedBreed)
    {
        case "Border Collie": _breedEnum = DogBreed.BorderCollie;
            break;
        case "Labrador Retriever": _breedEnum = DogBreed.LabradorRetriever;
            break;
        case "Pit Bull": _breedEnum = DogBreed.PitBull;
            break;
        //...
    }

    DoSomething(_breedEnum);
}
...

And our XAML

<Picker ItemsSource="{Binding BreedNames}" SelectedItem="{Binding SelectedBreed}"/>

As you can see, this is pretty gross…

Here’s a quick little strategy I use to make the binding process a little easier with my enums. It’s broken into just 3 quick parts:

  1. Create a extension methods to get a readable string from our `enum`
  2. Create a `Converter` to convert the `SelectedIndex` to the `enum` field
  3. Wire up the fields and XAML

Let’s create our enum extension methods to get a readable string for the UI:
StringExtensions.cs

    public static class StringExtensions
    {
        public static string SplitCamelCase(this string str)
        {
            return Regex.Replace(
                Regex.Replace(
                    str,
                    @"(\P{Ll})(\P{Ll}\p{Ll})",
                    "$1 $2"
                ),
                @"(\p{Ll})(\P{Ll})",
                "$1 $2"
            );
        }
    }

This SplitCamelCase method will take a string that is camel cased and split it out into separate words such as `”ThisIsMyValue”.SplitCamelCase(); // “This Is My Value”

Now that we have the ability to get a readable string from the enum values, let’s create our ViewModel properties we will need.

MyViewModel.cs

...
private DogBreed _selectedBreed;
public DogBreed SelectedBreed
{
    get
    {
        return _selectedBreed;
    }
    set
    {
        Set(ref _selectedBreed, value);
    }
}

public List<string> BreedNames
{
    get
    {
        return Enum.GetNames(typeof(DogBreed)).Select(b => b.SplitCamelCase()).ToList();
    }
}

public void DoSomethingWithBreed()
{
    DoSomething(SelectedBreed);
}
...

So much cleaner already. Now we need to create a Converter that our XAML can use to actually set the SelectedBreed property of our ViewModel.

IntEnumConverter.cs

    public class IntEnumConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Enum)
            {
                return (int)value;
            }
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value is int)
            {
                return Enum.ToObject(targetType, value);
            }
            return 0;
        }
    }

Last thing to do is use our IntEnumConverter and our properties to create our view in XAML:

MyView.xaml

<ContentPage.Resources>
    <ResourceDictionary>
        <converters:IntEnumConverter x:Key="IntEnum"/>
    </ResourceDictionary>
</ContentPage.Resources>
<Picker ItemsSource="{Binding BreedNames}" SelectedIndex="{Binding SelectedBreed, Converter=IntEnum}"/>

Here’s what we have!

Now you have the means to bind any of your Pickers quite easily to any of your custom enum fields!

“Woah! How did you get that Material Design Looking Picker on iOS”… Stay tuned!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Overriding Android Button Shadows/Elevation

Since Material Design’s implementation in the Android OS, some controls that ship with either the new styles, or with the App Compat packages place some under-the-cover restrictions on what you can do with the control by default. In this example, we will look at updating the App Compat Button Shadows and Elevation that ship with the control.

According to Material Design’s standards, “raised buttons” (versus flat buttons and floating action buttons) should have a resting elevation of 2dp, and an pressed/hover elevation of 8dp.

whatismaterial_3d_elevation_component02

This principle is also implemented in the App Compat Button. However, if you try to update the Elevation of your Button, you’ll notice that it won’t stay that way on the redraw, but will go right back to the 4dp it is by default.


supportButton.Elevation = 9; // set it directly
ViewCompat.SetElevation(supportButton, 9); // set using app compat method

...

Console.WriteLine(supportButton.Elevation); // will return 4...

So why is this? And how is Android creating the pressed animation automatically to increase the elevation? It certainly isn’t any code we’ve written. The answer is in the StateListAnimator property of the Button. The StateListAnimator is responsible for setting properties of the Button during certain states such as Enabled, Disabled, Focused, Pressed, etc. and is what is overriding the manual set of Button.Elevation.

You can override this in a few different ways to claim back full control. First, if you want to handle your different different states manually in your code, you can set the StateListAnimator to a new instance, or null, then set the Elevation to what you want.

In Code

supportButton.StateListAnimator = new StateListAnimator();
ViewCompat.SetElevation(supportButton, 9);

...

Console.WriteLine(supportButton.Elevation); // 9!

The most reusable way to do this is to subclass Button and set the StateListAnimator in the constructor:

CustomElevatingButton.cs

public class CustomElevatingButton : Android.Support.V7.Widget.AppCompatButton
{
    public CustomElevatingButton(Context context): base(context)
    {
        StateListAnimator = new StateListAnimator();
    }
}

Using Styles

Alternatively, you can set it using styles for your Button:

styles.xml

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:buttonStyle">@style/NoShadowButton</item>
    </style>
    <style name="NoShadowButton" parent="android:style/Widget.Button">
        <item name="android:stateListAnimator">@null</item>
    </style>
</resources>

You can also do it per-button:

 styles.xml

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        ...
    </style>
    <style name="NoShadowButton" parent="android:style/Widget.Button">
        <item name="android:stateListAnimator">@null</item>
    </style>
</resources>

some_layout.axml

...
<Button style="@style/NoShadowButton" ... />
...

In Xamarin.Forms

We can do the same thing in Xamarin.Forms with either a custom renderer or a custom Effect. In this example, we will create a universal Xamarin.Forms.Button custom renderer to set an explicit height:

ElevatedButtonRenderer

public class ElevatedButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
{
    public override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        StateListAnimator = null; // clear the state list animator
        Elevation = 9; // set the elevation
    }
}

Creating Your Own StateListAnimator

Of course, instead of clearing the StateListAnimator and handling your elevation manually, you could create your own to handle the states and animations however you want. Google has documentation included in the discussion about animations here. Here’s an example of creating and applying your own:

anim/reverse_state_list_animator.xml

<!-- animate the elevation property of a view when pressed -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true">
    <set>
      <objectAnimator android:propertyName="elevation"
        android:duration="@android:integer/config_shortAnimTime"
        android:valueTo="0dp"
        android:valueType="floatType"/>
        <!-- you could have other objectAnimator elements
             here for "x" and "y", or other properties -->
    </set>
  </item>
  <item android:state_enabled="true"
    android:state_pressed="false"
    android:state_focused="true">
    <set>
      <objectAnimator android:propertyName="elevation"
        android:duration="100"
        android:valueTo="2dp"
        android:valueType="floatType"/>
    </set>
  </item>
</selector>

This animation will do the reverse of the Material Design Standard, and will take the Button elevation from 2dp to 0dp when pressed.

Now we just need to apply this animation resource to our Button style either universally or on a specific button:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:buttonStyle">@style/NoShadowButton</item>
    </style>
    <style name="NoShadowButton" parent="android:style/Widget.Button">
        <item name="android:stateListAnimator">@anim/reverse_state_list_animator</item>
    </style>
</resources>

Now pressing any button within the AppTheme will reverse the elevation property and go more “into” the view rather than elevating.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Bringing Material Design Fonts to iOS

We might as well continue this trend of bringing Material Design to our iOS apps. Be sure to check out my previous posts on Material Frames in Xamarin.Forms iOS and Material Design Buttons in iOS (Native and Xamarin.Forms). Let’s talk about fonts now.

Material Design states that the preferred fonts to use are Roboto and Noto: https://material.io/guidelines/style/typography.html. These fonts ship in Android natively from Android 5.0+ (API Level 2.1) or when using the Android App Compat packages. However, these are not part of the OS in iOS, so if we want to fit a more Material Design standard, we need to bring those into our own apps.

Downloading and Installing the Fonts

First things first, we need to download both of these fonts from Google’s open web fonts.

  1. Roboto: https://fonts.google.com/specimen/Roboto
  2. Noto: https://fonts.google.com/specimen/Noto+Sans

You’ll need to make sure you don’t just download the Regular font files for both of these, but also each of the weights you’ll want to use in your app.

Now that you have all your .ttf files, you’ll need to bring them into your project. Place them in a folder at iOS Project > Resources > Font. Also make sure that each of their BuildActions are set to BundleResources. Do this by going to the Properties of each file and use the Build Action dropdown.
RobotoFontsInVS.PNG

The last step in getting them property installed is to update your Info.plist file to include the fonts. After this step, we’ll be able to start using it.

In Visual Studio, open your Info.plist file with the Generic PList Editor. When you do that, it should look something like this:
infoplistdefault

Scroll down to the bottom and add a new Property. You can use the dropdown to find it, or type it out yourself, but it needs to be Fonts provided by application. Set the type of this new item to Array, then start adding subitems for each of the fonts. For each font, you will need to set the type to String and the value to the path to your font from the Resources folder. So in our case, that will be something like Fonts/Roboto-Black.ttf.

Do this for each of your font files, and it should looks something like this:

infoplistfonts

Now we have our fonts installed into our iOS application, we can start using them!

Using the Font in Xamarin.iOS Native

Now that our application is aware of our font, we can apply it to any UILabel we instantiate in our code:

ExampleViewController.cs

var label = new UILabel(new RectangleF(0,0, width, height /2));
label .Text = "This is a label using Roboto";
label .Font = UIFont.FromName("Roboto-Regular", 20f);
this.Add(label);

Alternatively, we can use the Appearance APIs to apply it to all of our UILabels across our app:

AppDelegate.cs

public class AppDelegate : UIApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        ...

        UILabel.Appearance.Font = UIFont.FromName("Roboto-Regular", 20f);
        ...
        return true;
    }
}

Using the Font in Xamarin.Forms iOS

Of course, we also might need to use this font in Xamarin.Forms! Just like in native iOS, we need to apply our font, by name to any given label we want, or we can use Styles to apply it everywhere.

ExamplePage.xaml

<ContentPage ...>
    <Label FontFamily="Roboto-Regular" FontSize="20" Text="Xamarin.Forms Roboto on iOS"/>
</ContentPage>

or:

App.xaml

<Application ...>
    <Application.Resources>
        <ResourceDictionary>
<Style TargetType="Label">
                <Setter Property="FontFamily" Value="Roboto-Regular"/>
                ...
            </Style>

        </ResourceDictionary>
    </Application.Resources>
</Application>

Results

Now we have our nicer looking fonts from Material Design applied to our iOS apps. Look at this comparison of some default iOS Frames and Fonts versus our new Materialized look and feel:

Old (Defaults)
iOSDefaultFrameAndLabel

New (Custom Frame and Roboto-Regular Font)
iOSMaterialFrameAndLabel

Are there any other controls you’d like to see Materialized on iOS? Let me know in the comments!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Creating a Material Design Button in iOS

As per requests after my last post on creating a more Material looking Xamarin.Forms Frame on iOS, I’ll start talking about bringing a more material design feel to other controls in iOS. This time we’ll look at getting a more material Button control, first to be usable without Xamarin.Forms, then in a custom renderer that we can use everywhere and apply to all our Buttons.

Keep in mind, this does not hit upon all the pieces of a Material Design Button that you might see in Android. For example, it does not show a ripple on tap, and does not raise the elevation on tap. Those topics will come in a different blog post!

Let’s get down to it with a custom UIButton that applies a material-ish shadow to our button.

MaterialButton.cs

    public class MaterialButton : UIButton
    {
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            // don't do it on transparent bg buttons
            if (BackgroundColor.CGColor.Alpha == 0)
                return;

            // Update shadow to match better material design standards of elevation
            Layer.ShadowRadius = 2.0f;
            Layer.ShadowColor = UIColor.Gray.CGColor;
            Layer.ShadowOffset = new CGSize(2, 2);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromRect(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;
        }
    }

You can see that we basically just apply a specific shadow to our base Layer of the control.

Now, let’s interpret this into a custom renderer for Xamarin.Forms:

MaterialButtonRenderer.cs

[assembly: ExportRenderer(typeof(Button), typeof(MaterialButtonRenderer))]
namespace YOUR_IOS_NAMESPACE
{
    public class MaterialButtonRenderer : ButtonRenderer
    {
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            // don't do it on transparent bg buttons
            if (Element.BackgroundColor.A == 0)
                return;

            // Update shadow to match better material design standards of elevation
            Layer.ShadowRadius = 2.0f;
            Layer.ShadowColor = UIColor.Gray.CGColor;
            Layer.ShadowOffset = new CGSize(2, 2);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromRect(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;

        }
    }
}

This will apply the shadow to any regular Button Element. If you want to create a whole new Element that will allow you to use it in specific places, you could either create an Effect, or you can create a new class that subclasses Xamarin.Forms.Button, and then update the renderer to fit that class:

MaterialButton.xaml.cs

public partial class MaterialButton : Button
{
    // we don't need to do anything special here since we do all the custom work in the iOS Renderer
}

and of course our updated renderer

MaterialButtonRenderer.cs

[assembly: ExportRenderer(typeof(MaterialButton), typeof(MaterialButtonRenderer))]
namespace YOUR_IOS_NAMESPACE
{
    public class MaterialButtonRenderer : ButtonRenderer
    {
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            // don't do it on transparent bg buttons
            if (Element.BackgroundColor.A == 0)
                return;

            // Update shadow to match better material design standards of elevation
            Layer.ShadowRadius = 2.0f;
            Layer.ShadowColor = UIColor.Gray.CGColor;
            Layer.ShadowOffset = new CGSize(2, 2);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromRect(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;

        }
    }
}

Now your control should go from this:

iOSRegularButton

To this:

iOSMaterialButton

Make sure to stay tuned for more Material Design styled controls brought to iOS, and adding some advanced features like rippled clicks and elevation changes/settings.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Making Your iOS Frame Shadows More Material

If you’ve used the Xamarin.Forms Frame element on iOS and have HasShadow set to true, then you might notice that on iOS, the shadow is quite abrasive and overwhelming.

We can update just the iOS FrameRenderer to create some better shadows, so we can go from this:

DefaultiOSFrameShadow

to this:

iOSMaterialShadow

In order to override all Frame elements, we will need to create our custom renderer and also set it to export to the default Frame. If you do not want it to apply to all Frames, then you can create a custom control that inherits from frame and then apply the renderer to that new element type. We’ll example both here:

MaterialFrameRenderer.cs


[assembly: ExportRenderer(typeof(Frame), typeof(MaterialFrameRenderer))]
namespace YOU_IOS_NAMESPACE
{
    /// <summary>
    /// Renderer to update all frames with better shadows matching material design standards
    /// </summary>

    public class MaterialFrameRenderer : FrameRenderer
    {
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            // Update shadow to match better material design standards of elevation
            Layer.ShadowRadius = 2.0f;
            Layer.ShadowColor = UIColor.Gray.CGColor;
            Layer.ShadowOffset = new CGSize(2, 2);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromRect(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;
        }
    }
}

That’s all you need in your iOS project in order to apply it everywhere. Now, if you want to apply it to a new custom Element, we can create it and apply it like so:

MaterialFrame.xaml.cs


namespace YOUR_PCL_NAMESPACE
{
    public class MaterialFrame : Frame
    {
        // no other code needs to go here unless you want more customizable properties.
    }
}

Then create your renderer and export it for you new Element:

MaterialFrameRenderer.cs


[assembly: ExportRenderer(typeof(MaterialFrame), typeof(MaterialFrameRenderer))]
namespace YOU_IOS_NAMESPACE
{
    /// <summary>
    /// Renderer to update all frames with better shadows matching material design standards
    /// </summary>

    public class MaterialFrameRenderer : FrameRenderer
    {
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            // Update shadow to match better material design standards of elevation
            Layer.ShadowRadius = 2.0f;
            Layer.ShadowColor = UIColor.Gray.CGColor;
            Layer.ShadowOffset = new CGSize(2, 2);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromRect(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;
        }
    }
}

And now your frames can look much nicer~

iOSMaterialShadow

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Fixing the Highlighting Drop In Your Xamarin.Android Projects

I’ve seen a few people run into this issue in both Visual Studio 2015 and 2017. For those of you who don’t know what I’m talking about, the issue is that code highlighting drops completely in newly opened files. I’ve personally seen it happen in both Xamarin.Forms PCLs and in Xamarin.Android projects. The reason you lose your highlighting is because the project fails to load properly, and your files will then open as “Miscellaneous Files”:

MiscFilesError

These should be opening up as part of the project and thus getting the references required for highlighting, so the goal here is to fix the project load and get these files to open as part of that project.

So here are a few steps that have worked for everyone who has reached out for help:

  1. Don’t panic! This will be quick.
  2. Try unloading the project and reloading it (Right click the project in the Solution Explorer > Unload Project, Right click > Reload Project)
  3. Still happening when you open files in that project? Keep reading.
  4. Check your Error List, there might be warnings to give you hints here.

In this post, we will look at resolving the issue for Xamarin.Android projects. If you are looking for resolving issues in your Xamarin.Forms PCL projects look at this earlier post: Xamarin.Tips – Fixing the Highlighting Drop In Your Xamarin.Forms Projects

Xamarin.Android Project Issues

There are two common issues that are particular to Xamarin.Android projects that cause this.

Dependencies aren’t built

The first is a known bug in Xamarin projects (especially when first created). The problem is that it relies on it’s dependencies to load properly, however, if you have not built one or more of the projects that the Android project depends on, you will get this load error:

Warning1

along with it’s partner:

Warning2

However, you may have seen this and followed the steps listed without fixing anything or learning more about the issue:

1. Close Visual Studio
2. Open a Visual Studio Developer Command Prompt
3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true)
4. Delete .vs directory/.suo file
5. Restart VS from the command prompt you set the environment variable (devenv)
6. Open the solution

THE SOLUTION:
1. Unload the Android project
2. Build all the other projects in your solution
3. Reload your Android project

A Corrupt or Broken Android Resource

This one can be elusive because it does not always throw errors or warnings, but is also quite common. The problem is that one of your Android resources has an error. This is likely in your layouts or your values folders.

THE SOLUTION:
1. Go through your error list for warnings about your Android resources
2. If you have any issues there, fix those problems and unload > reload the Android project.
3. If you do NOT see any items in your Error List, go through each of your layout and value files (like colors.xml and styles.xml) and search for errors. They are more likely to show warning squiggles in your editor.
4. Resolve all issues and unload > reload the Android project.

 

If none of these solutions fixed your problem, read below for more generic solutions for this issue.

Refresh Your Intellisense Cache

Your Intellisense cache could be corrupt, so try clearing it. Close all your open files then:

Edit > IntelliSense > Refresh Local Cache 

Or Ctrl + Shift + R

Clearing Your Local Data

Close Visual Studio Completely, then go to %appdata%\Microsoft\VisualStudio{your_version_number}\ReflectedSchemas and delete all the content.

Reset your Visual Studio Settings

In Visual Studio, go to Tools > Import and Export Settings and hit Reset all settings.

Restart Visual Studio.

Fix All Errors and Warnings In the Error List

Similarly to how we talked about fixing your XAML error, try making sure all of your errors and warnings are fixed. Some other common issues that can cause the project to load with errors include:

  1. Circular References
  2. Missing project references
  3. Failed nuget downloads
  4. Duplicate files
  5. Broken/wrong typed partial classes

 

Still Not Working?

Leave a comment describing all the detail you can about the errors and warnings you are seeing and we can work together to fix your problems!

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Controls – Xamarin.Forms FloatingActionButton (including iOS!)

You did actually read that title correctly – we have a FloatingActionButton to use in Xamarin.Forms that works in both Android and iOS!

I’ve put the source code up for this here: https://github.com/SuavePirate/Xamarin.Forms.Controls.FloatingActionButton

It’s rudimentary and has room for some more fun properties, but it is fully functional! If you would like to contribute to the repository, see the TODO: list at the bottom of the README and start forking and making pull requests!

To breakdown the steps to create your own Floating Action Button in Xamarin.Forms, you’ll need:

  1. A custom Xamarin.Forms `Element`
  2. An Android Custom renderer to use the native `Android.Compat.Design.Widgets.FloatingActionButton`
  3. An iOS Custom renderer to create a button that looks like a FAB.

So let’s go in that order.

In Xamarin.Forms PCL

FloatingActionButton.xaml.cs

  public partial class FloatingActionButton : Button
    {
        public static BindableProperty ButtonColorProperty = BindableProperty.Create(nameof(ButtonColor), typeof(Color), typeof(FloatingActionButton), Color.Accent);
        public Color ButtonColor
        {
            get
            {
                return (Color)GetValue(ButtonColorProperty);
            }
            set
            {
                SetValue(ButtonColorProperty, value);
            }
        }
        public FloatingActionButton()
        {
            InitializeComponent();
        }
    }

We added a new BindableProperty for the ButtonColor. This is done because setting the BackgroundColor will mess up the Android renderer and apply the background behind the FAB. We want to inherit from Button so that we can utilize some of the already useful properties that come with it – namely the Image property that consumes a FileImageSource. We can use this to set the icon for our FAB.

In Android

FloatingActionButtonRenderer.cs

using FAB = Android.Support.Design.Widget.FloatingActionButton;

[assembly: ExportRenderer(typeof(SuaveControls.Views.FloatingActionButton), typeof(FloatingActionButtonRenderer))]
namespace SuaveControls.FloatingActionButton.Droid.Renderers
{
    public class FloatingActionButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ViewRenderer<SuaveControls.Views.FloatingActionButton, FAB>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<SuaveControls.Views.FloatingActionButton> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null)
                return;

            var fab = new FAB(Context);
            // set the bg
            fab.BackgroundTintList = ColorStateList.ValueOf(Element.ButtonColor.ToAndroid());

            // set the icon
            var elementImage = Element.Image;
            var imageFile = elementImage?.File;

            if (imageFile != null)
            {
                fab.SetImageDrawable(Context.Resources.GetDrawable(imageFile));
            }
            fab.Click += Fab_Click;
            SetNativeControl(fab);

        }
        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);
            Control.BringToFront();
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var fab = (FAB)Control;
            if (e.PropertyName == nameof(Element.ButtonColor))
            {
                fab.BackgroundTintList = ColorStateList.ValueOf(Element.ButtonColor.ToAndroid());
            }
            if (e.PropertyName == nameof(Element.Image))
            {
                var elementImage = Element.Image;
                var imageFile = elementImage?.File;

                if (imageFile != null)
                {
                    fab.SetImageDrawable(Context.Resources.GetDrawable(imageFile));
                }
            }
            base.OnElementPropertyChanged(sender, e);

        }

        private void Fab_Click(object sender, EventArgs e)
        {
            // proxy the click to the element
            ((IButtonController)Element).SendClicked();
        }
    }
}

A few important things to point out:

  • We add the additional using statement `using FAB = Android.Support.Design.Widget.FloatingActionButton;` to help us distinguish between our Xamarin.Forms element and the built in Android control.
  • We are NOT using a `ButtonRenderer` as our base class, but instead using a basic `ViewRenderer`. This is because the underlying control will not be a native Android `Button`, but the native Android `FloatingActionButton`.
  • Because we replace the `ButtonRenderer`, we need to make sure we still propagate click events up to the Xamarin.Forms element.

Now let’s look at iOS, which can utilize more of the built in pieces from Xamarin.Forms since it supports the BorderRadius property on Buttons.

In iOS

FloatingActionButtonRenderer.cs

[assembly: ExportRenderer(typeof(SuaveControls.Views.FloatingActionButton), typeof(FloatingActionButtonRenderer))]
namespace SuaveControls.FloatingActionButton.iOS.Renderers
{
    [Preserve]
    public class FloatingActionButtonRenderer : ButtonRenderer
    {
        public static void InitRenderer()
        {
        }
        public FloatingActionButtonRenderer()
        {
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null)
                return;

            // remove text from button and set the width/height/radius
            Element.WidthRequest = 50;
            Element.HeightRequest = 50;
            Element.BorderRadius = 25;
            Element.BorderWidth = 0;
            Element.Text = null;

            // set background
            Control.BackgroundColor = ((SuaveControls.Views.FloatingActionButton)Element).ButtonColor.ToUIColor();
        }
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);
            // add shadow
            Layer.ShadowRadius = 2.0f;
            Layer.ShadowColor = UIColor.Black.CGColor;
            Layer.ShadowOffset = new CGSize(1, 1);
            Layer.ShadowOpacity = 0.80f;
            Layer.ShadowPath = UIBezierPath.FromOval(Layer.Bounds).CGPath;
            Layer.MasksToBounds = false;

        }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == "ButtonColor")
            {
                Control.BackgroundColor = ((SuaveControls.Views.FloatingActionButton)Element).ButtonColor.ToUIColor();
            }
        }
    }
}

We set an explicit WidthRequest, HeightRequest, and BorderRadius to get ourselves a circle. I’m not a big fan of doing it here, since it’s better suited as a calculation, but for now it works.

Lastly in our Draw override, we set up the drop shadow behind out button, and make sure that our ShadowPath is actually built from an oval so that it rounds off with the Button.
Also note that we take the ButtonColor property and apply it as the BackgroundColor of the UIButton to override the color from Xamarin.Forms. Don’t forget to set Text to null so that we can’t add text to the button and mess it up.

As a side note, iOS might try to link our your custom renderer if you are using it in an iOS Class Library. In order to avoid this, make sure to call a static InitRenderer method in your AppDelegate.cs as it will prevent it from being linked out.

Using the FloatingActionButton

Now that we have our renderers registered for our new Element, we can use it in our XAML or C# of our PCL or Shared Project:

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"              xmlns:local="clr-namespace:SuaveControls.FabExample"              xmlns:controls="clr-namespace:SuaveControls.Views;assembly=SuaveControls.FloatingActionButton"              x:Class="SuaveControls.FabExample.MainPage">
    <StackLayout Margin="32">
        <Label Text="This is a Floating Action Button!"             VerticalOptions="Center"             HorizontalOptions="Center"/>

        <controls:FloatingActionButton x:Name="FAB" HorizontalOptions="CenterAndExpand" WidthRequest="50" HeightRequest="50"  VerticalOptions="CenterAndExpand" Image="ic_add_white.png" ButtonColor="#03A9F4" Clicked="Button_Clicked"/>
    </StackLayout>
</ContentPage>

and our code behind:

MainPage.xaml.cs

namespace SuaveControls.FabExample
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            await DisplayAlert("FAB Clicked!", "Congrats on creating your FAB!", "Thanks!");
        }
    }
}

Then we get these results in our Android and iOS apps:

Android

Screenshot_1493173400

iOS

2017-04-25_10-38-38-PM

If you want to just pull down the control I built on GitHub, the steps are straight forward:

  1. Clone the repository
  2. Reference the PCL in your PCL/Shared Lib
  3. Reference the PCL and native projects in your respective native project
  4. Pull the namespace into your XAML (or C#)
  5. Start using it!

The repository also contains an example app that references the source libraries.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Fixing the Highlighting Drop In Your Xamarin.Forms Projects

I’ve seen a few people run into this issue in both Visual Studio 2015 and 2017. For those of you who don’t know what I’m talking about, the issue is that code highlighting drops completely in newly opened files. I’ve personally seen it happen in both Xamarin.Forms PCLs and in Xamarin.Android projects. The reason you lose your highlighting is because the project fails to load properly, and your files will then open as “Miscellaneous Files”:
MiscFilesError

These should be opening up as part of the project and thus getting the references required for highlighting, so the goal here is to fix the project load and get these files to open as part of that project.

So here are a few steps that have worked for everyone who has reached out for help:

  1. Don’t panic! This will be quick.
  2. Try unloading the project and reloading it (Right click the project in the Solution Explorer > Unload Project, Right click > Reload Project)
  3. Still happening when you open files in that project? Keep reading.
  4. Check your Error List, there might be warnings to give you hints here.

In this post, we will look at resolving the issue for Xamarin.Forms PCL projects, and will look at fixes for Xamarin.Android projects in another article.

Xamarin.Forms PCL Issues

The most common issue here is that there is an issue in your XAML. For some reason, XAML errors/warnings can throw off the entire project load.

Here’s a quick look at what that might look like:

XamlErrors

  1. From your Error List view, find the XAML page culprit.
  2. Fix the error in your XAML file.
  3. Close all files in the project that is having issues.
  4. In the Solution Explorer, click the refresh button at the top.SolutionRefresh
  5. Re-open the files that were breaking, and you should see everything is back to normal.

Didn’t solve your problem? Let’s look at some of the conventional fixes for this then:

Refresh Your Intellisense Cache

Your Intellisense cache could be corrupt, so try clearing it. Close all your open files then:

Edit > IntelliSense > Refresh Local Cache 

Or Ctrl + Shift + R

Clearing Your Local Data

Close Visual Studio Completely, then go to %appdata%\Microsoft\VisualStudio{your_version_number}\ReflectedSchemas and delete all the content.

Reset your Visual Studio Settings

In Visual Studio, go to Tools > Import and Export Settings and hit Reset all settings.

Restart Visual Studio.

Fix All Errors and Warnings In the Error List

Similarly to how we talked about fixing your XAML error, try making sure all of your errors and warnings are fixed. Some other common issues that can cause the project to load with errors include:

  1. Circular References
  2. Missing project references
  3. Failed nuget downloads
  4. Duplicate files
  5. Broken/wrong typed partial classes

 

Looking for solving this problem for your Android projects? Stay tuned for another post about some of the Android specific issues that might be causing project load fails.

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.