Mr.Buntha Khin
Mr.Buntha Khin

Reputation: 85

Error when try to customize font in xamarin.android

I used xamarin.android for develop app, I tried to customize font with code:

 Typeface myfont = Typeface.CreateFromAsset (Context.Assets, "fonts/KhmerOS.ttf");

but when I built, it error as shown bellow:

Error CS0120: An object reference is required for the non-static field, method, or property 'Android.Content.Context.Assets.get' (CS0120)

please help me,

Best Regard Buntha

Upvotes: 2

Views: 1955

Answers (4)

Maury
Maury

Reputation: 604

Try this :)

[assembly: ExportRenderer(typeof(Label), typeof(MyLabelRenderer))]
namespace App3.Droid.Debug
{
    class MyLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
        base.OnElementChanged(e);

        var label = (TextView)Control;
        Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "your font name.otf/ttf");
        label.Typeface = font;
    }
}
}

Note: Put Fonts to Assets and set property "Build Action on AndroidAsset and Copy to Output Directory to Copy Always"

Upvotes: 1

Suchith
Suchith

Reputation: 1527

This may be the late reply but might help someone with the same issue. Set BuilAction to Android Asset for font file. (Right click on fontfile->BuildAction select AndroidAsset)

Upvotes: 4

Naruto Uzumaki
Naruto Uzumaki

Reputation: 2087

Try this:

Typeface tf = Typeface.CreateFromAsset(Application.Context.Assets, "fonts/KhmerOS.ttf");

Upvotes: 2

user3355820
user3355820

Reputation: 272

Edit your code as

Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font name.ttf");
tx.setTypeface(custom_font);

Upvotes: 0

Related Questions