如何在单个位置为整个Xamarin.Android应用程序设置fontFamily?

问题描述 投票:0回答:2

我通常要设置工具栏的文本,按钮,TextViews以及Xamarin.Andrid应用程序的所有文本的fontFamily。如何在一个地方做到这一点?我尝试将以下内容放入Base application themestyles.xml中:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    .....
    <item name="fontFamily">@drawable/Exo2_ExtraBold</item>
    .....
</style>

但是它仅更改了fontFamilyMainActivity,我想这是因为只有该活动在其上方具有Theme = "@style/AppTheme"属性。如果我将该属性放在其余活动的上方,那么我想它也可以使用,但是难道没有一种更简单的方法来实现所有应用程序在一个应用程序中的单个位置设置一个fontFamily吗?另外,我也将.otf文件放在我手动创建的drawables文件夹中的font文件夹中,但是在尝试重建解决方案时却给了我一个错误。因此,我想知道如何将.oft放入正确的文件夹中。

xamarin.android set font-family
2个回答
0
投票

[当我们创建新的Activity时,其超类默认为Activity。因此,我们应该手动将其更改为AppCompatActivity。并添加行Theme = "@style/AppTheme"

using Android.Support.V7.App;
[Activity(Label = "Activity1", Theme = "@style/AppTheme")]
public class Activity1 : AppCompatActivity

0
投票

在android中使用自定义字体的最简单方法是使用Calligraphy,对于Xamarin,您可以使用Calligraphy.Xamarin

  1. 将您的自定义字体,例如:my-custom-font.ttf复制到fonts目录中的assets目录。
  2. 添加Calligraphy.Xamarin nuget包Install-Package Calligraphy.Xamarin

  3. 创建一个类,例如:Startup并向其中添加以下内容:

[Application]
public class Startup : Application
{   
    public Startup(IntPtr javaReference, JniHandleOwnership transfer)
        : base(javaReference, transfer) { }

    public override void OnCreate()
    {
        base.OnCreate();

        CalligraphyConfig.InitDefault(
            new CalligraphyConfig.Builder()
                .SetDefaultFontPath("fonts/my-custom-font.ttf")
                .SetFontAttrId(Resource.Attribute.fontPath)
                .Build()
        );      
    }
}
  1. Activities中添加以下代码,您可以开始使用。
protected override void AttachBaseContext(Context context)
{
    base.AttachBaseContext(Calligraphy.CalligraphyContextWrapper.Wrap(context));
}

您可以创建一个基本活动,以避免向每个活动中添加以上代码。

© www.soinside.com 2019 - 2024. All rights reserved.