将自定义字体添加到attrs.xml

问题描述

我有一个使用自定义字体的android应用程序,我们称它为my_font.ttf,我将其保存在font包的res文件夹中。

我还有一个自定义数字选择器,需要在其中为选择器中的值设置字体。这是我的attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NumPicker">
   
        <attr name="max" format="integer" />
        <attr name="min" format="integer" />
        <attr name="selectedTextColor" format="color" />
        <attr name="selectedTextSize" format="float" />
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />

        <attr name="typeface" format="enum">
            <enum name="font" value="0"/>
            <enum name="sans" value="1"/>
            <enum name="serif" value="2"/>
            <enum name="monospace" value="3"/>
        </attr>
        
    </declare-styleable>
</resources>

我想知道如何将my_font.ttf添加到此attrs.xml中,以便可以在布局文件中使用它来设置字体。像那些serif,sans,monospace一样,它们都是内置字体,但我不确定如何使用我的字体。

这是我的layout文件,它使用了自定义NumPicker

<com.myproject.slidertest.selectors.numberpicker.NumPicker
            android:id="@+id/numberPicker"
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            android:paddingLeft="40dp"
            android:paddingRight="40dp"
            android:layout_gravity="center_horizontal"
            app:typeface="serif"<!-- I want to be able to change this font to my font-->
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:selectedTextColor="@color/color_blue"
            app:textColor="@color/colorTextDefault"
            app:max="50"
            app:min="10"
          />

任何帮助或建议将不胜感激。

解决方法

添加另一个属性

<attr fontTextAppearance format="reference">

在自定义视图中,如果字体类型为font,请查找typefaceFont引用。

val textAppearance = ta.getResourceId(R.styleable.NumPicker_fontTextAppearance,-1)
        if (textAppearance != -1) {
            textView.setTextAppearance(textAppearance)
        }



 

 <com.myproject.slidertest.selectors.numberpicker.NumPicker
        android:id="@+id/numPicker"
        style="@style/NumPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:fontTextAppearance="@style/NumPickerFont"
      />

 <style name="NumPickerFont">
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">40sp</item>
    <item name="android:textAlignment">viewStart</item>
    <item name="android:letterSpacing">0.18</item>
    <item name="android:fontFamily">@font/some_font</item>
</style>