Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a custom font in Xamarin.Android?

I understand how to add a .tff file into my project but I haven't been able to find a post that makes it clear how and where to implement the font once it's been added. I found a post that says to implement the font like this:

var typeface = Typeface.CreateFromAsset (context.Assets, fileName);

But I don't know where I should add this line of code, or what I should use in place of context. Can someone give me a basic explanation so I know what I'm missing?

like image 973
michael__sloan Avatar asked Dec 10 '22 15:12

michael__sloan


2 Answers

Using a template created Xamarin.Android single Activity application:

Add a font to the Assets directory with a build type of AndroidAsset:

├── Assets
│   ├── AboutAssets.txt
│   └── Jellee-Roman.ttf

In the OnCreate add the following:

Button button = FindViewById<Button>(Resource.Id.myButton);

// Add these two lines:
var font = Typeface.CreateFromAsset(Assets, "Jellee-Roman.ttf");  
button.Typeface = font;

button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
like image 149
SushiHangover Avatar answered Jan 16 '23 04:01

SushiHangover


Once you have the reference to the Typeface, you can then set it into the TextView via the following:

Typeface property - https://developer.xamarin.com/api/property/Android.Widget.TextView.Typeface/

SetTypeface method - https://developer.xamarin.com/api/member/Android.Widget.TextView.SetTypeface/p/Android.Graphics.Typeface/Android.Graphics.TypefaceStyle/

like image 23
Jon Douglas Avatar answered Jan 16 '23 05:01

Jon Douglas