【问题标题】:Font asset not found exception in the Xamarin Android designer page(main.axml)在 Xamarin Android 设计器页面 (main.axml) 中找不到字体资产异常
【发布时间】:2020-01-24 16:34:04
【问题描述】:
  1. Designer 在使用 Assets 文件夹中的 ttf 文件时崩溃。
  2. 在我的代码中,我使用 ttf 文件来设置 TextView 字体属性(如 Typeface = Typeface.CreateFromAsset(this.Context.Assets, "fonts/Sample_Icons.ttf"),
  3. 它使我的设计器页面崩溃。

请给我建议。

【问题讨论】:

    标签: xamarin.android


    【解决方案1】:

    将ttf文件放入Assets文件夹后,可以通过以下方法访问ttf文件:

     AssetManager assets = this.Assets;
     Typeface font = Typeface.CreateFromAsset(assets, "Lobster-Regular.ttf");
    
     // and use like this
     Button button = (Button)FindViewById(Resource.Id.btn);
     button.SetTypeface(font, TypefaceStyle.Normal);
    

    也就是说,你只需要去掉ttf文件前的fonts,你可以这样使用:

    Typeface.CreateFromAsset(this.Assets, "Sample_Icons.ttf");
    

    而不是:

    Typeface.CreateFromAsset(this.Context.Assets, "fonts/Sample_Icons.ttf");
    

    有一个简单的demo,可以查看here。效果如下:

    【讨论】:

    • 我已经按照你说的修改了代码,但问题仍然存在
    • @Santhiya 我在答案中分享了一个简单的演示链接,你可以查看。
    【解决方案2】:

    我使用了基于这篇文章的解决方案:

    https://blog.mzikmund.com/2017/07/checking-for-design-mode-in-xamarin-forms/

    public static class EmulatorHelper
    {
        // https://blog.mzikmund.com/2017/07/checking-for-design-mode-in-xamarin-forms/
        public static bool IsDesigner { get; set; }
        #if !RELEASE
            = true;
        #endif
    }
    

    然后在应用程序的某个地方启动,例如 AndroidApp.cs

    public class AndroidApp : App
    {
        public override void Initialize()
        {
            base.Initialize();
            EmulatorHelper.IsDesigner = false;
        }
    }
    

    最后替换

    Typeface font = Typeface.CreateFromAsset(assets, "Lobster-Regular.ttf");
    

    Typeface font = !EmulatorHelper.IsDesigner 
        ? Typeface.CreateFromAsset(assets, "Lobster-Regular.ttf")
        : Typeface.Default;
    

    此解决方案的缺点是您会在设计器中看到默认字体,但它比带有错误标签的橙色框要好得多:)

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2016-08-13
      • 1970-01-01
      • 2021-10-07
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多