Changing Font of text on Button

Hi everyone,

I am working on a xamarin forms app and I need to change the font based on platform.
For labels I am using the below code
public class CustomLabelRenderer : LabelRenderer
{

    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        var label = (TextView)Control; // for example
        Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Roboto-Regular.ttf");  // font name specified here
        label.Typeface = font;
    }

}

But for changing the font of text on button What should I do ?
Please guide.
Thanks

Best Answer

Answers

  • JohnHardmanJohnHardman GBUniversity mod

    @AmitKumar.8556 - the Xamarin.Forms.Button has three properties that should be used to specify the font - FontAttributes, FontFamily and FontSize.

    You can use Device.OnPlatform to specify these properties for different platforms, as follows:

                button.FontAttributes = FontAttributes.Bold;
                button.FontFamily = Device.OnPlatform("MarkerFelt-Thin", "Roboto", "Verdana");
                button.FontSize = Device.GetNamedSize(
                    Device.OnPlatform(NamedSize.Large, NamedSize.Small, NamedSize.Medium), typeof(Button));
    

    (I typed that from memory, so forgive any typo's)

  • AmitKumar.8556AmitKumar.8556 INMember ✭✭

    John I tried this code

    button.FontFamily = Device.OnPlatform("MarkerFelt-Thin", "Roboto", "Verdana");

    but its not working in android buttons, only default font is being displayed which is selected in device. (I am using samsung s7 for testing).

    Do you know any other solution. ?

  • AmitKumar.8556AmitKumar.8556 INMember ✭✭

    Thanks for your support John :)
    Its working for me now, I used the following code

    var label = (Android.Widget.Button)Control; // for example
    Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Roboto-Regular.ttf");  // font name specified here
    label.Typeface = font;

  • UmairAli.4023UmairAli.4023 USMember ✭✭
    edited September 2016

    Can I use two fonts like for icon font awesome and other for text in same label or button?

Sign In or Register to comment.