CallygraphyXamarin无法在MvxAppCompatActivity中工作

时间:2017-02-08 05:45:05

标签: xamarin xamarin.android mvvmcross

我已经花了好几个小时试图在我的MvvmCross项目中使用自定义字体,特别是Android平台。 我成功安装了组件并按照上述步骤操作: https://components.xamarin.com/gettingstarted/calligraphyxamarin

它只是不想工作。

我在活动上对其进行了测试,而不是继承自ActivityAppCompatActivity这两项活动。 似乎继承自MvxAppCompatActivity打破了它?这个问题解决了吗?

1 个答案:

答案 0 :(得分:7)

更新

我为此发布了一个nuget包(参见:MvvmCross.Calligraphy)。

只需下载并修改您的设置,如:

public class Setup : MvxAndroidSetup
{
    protected override MvxAndroidBindingBuilder CreateBindingBuilder()
    {
        return new CalligraphyMvxAndroidBindingBuilder();
    }
}

是的,因为MvvmCross使用自定义布局充气器来引入绑定和其他一些神奇的东西。这推出了书法充气机。不幸的是,我没有找到使用nuget package / xamarin组件的方法。您必须创建自己的绑定并使CalligraphyFactory可用。

修改后的metadata.xml

<attr path="/api/package[@name='uk.co.chrisjenx.calligraphy']/class[@name='CalligraphyFactory']" 
      name="visibility">public</attr>

自定义工厂

public class MyFactory : MvxAndroidViewFactory
{
    private CalligraphyFactory _factory;

    public MyFactory()
    {
        _factory = new Calligraphy.CalligraphyFactory(Resource.Attribute.fontPath);
    }

    public override View CreateView(View parent, string name, Context context, IAttributeSet attrs)
    {
        var view = base.CreateView(parent, name, context, attrs);
        view = _factory.OnViewCreated(view, context, attrs);
        return view;
    }
}

自定义绑定构建器

class MyBindingBuilder : MvxAndroidBindingBuilder
{
    protected override IMvxAndroidViewFactory CreateAndroidViewFactory()
    {
        return new MyFactory();
    }
}

<强> Setup.cs

public class Setup : MvxAndroidSetup
{
    protected override MvxAndroidBindingBuilder CreateBindingBuilder()
    {
        return new MyBindingBuilder();
    }
    // ...
}

<强>活动

您不需要AttachBaseContext。不幸的是,似乎无法使用MvxAppCompatActivity,但使用MvxActivity。我还不确定导致此问题的原因。

public class FirstView : MvxActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        CalligraphyConfig.InitDefault(new CalligraphyConfig.Builder()
           .SetDefaultFontPath("fonts/gtw.ttf")
           .SetFontAttrId(Resource.Attribute.fontPath)
           .DisablePrivateFactoryInjection()
           .Build());

        SetContentView(Resource.Layout.FirstView);
    }
}

查看

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="40dp"
    local:MvxBind="Text Hello"
    />
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="40dp"
    local:MvxBind="Text Hello"
    fontPath="fonts/gtw.ttf"
    />
</LinearLayout>

<强>结果

custom font