cniak
cniak

Reputation: 311

Default font for project from asset folder

I have the following code in my Activity to change the font for some ViewGroup in a layout:

setFont("fonts/texgyreheros-regular-webfont.ttf", listBold, TypefaceStyle.Bold);

The definition of setFont is as follows:

private void setFont(string path, List<TextView> tTV, TypefaceStyle Type)
{
    Android.Content.Res.AssetManager mgr;
    mgr = Assets;
    Typeface font = Typeface.CreateFromAsset(mgr, path);
    for (int i = 0; i < tTV.Count; i++)
    {
        tTV[i].SetTypeface(font, Type);
    }
}

listBold is a List<TextView> which is populated by calling:

findViewById<TextView>(Resource.Id.(...));

multiple times.

Is there any way to avoid this step by setting the default font in Android manifest.xml or somwhere else?

Upvotes: 0

Views: 355

Answers (1)

QArea
QArea

Reputation: 4981

You can create a custom TextView with your font from assets.

public class TextViewWithFont : TextView {
    private const string FONT = "fonts/font.ttf";

    public TextViewWithFont(Context context) : base(context) {
        SetTypeface(Typeface.CreateFromAsset(context.Assets, FONT));
    }
}

Then use this class in layout.

<com.example.views.TextViewWithFont
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/>

Upvotes: 1

Related Questions