为 android 添加自定义字体 api 14

Adding custom fonts for android api 14

错误
错误:未找到样式属性 'app:attr/fontFamily'。 消息{种类=错误,文本=错误:未找到样式属性 'app:attr/fontFamily'。

<style name="RadioButtonCustomStyle" parent="Widget.AppCompat.CompoundButton.RadioButton">
    <item name="android:textColorPrimaryDisableOnly">#f44336</item>
    <item name="android:textColor">#607ba3</item>
    <item name="app:fontFamily">@font/raleway_medium</item>
</style>

我在app/assets/font/raleway_medium.ttf

中添加了raleway_medium.ttf

在您的文件夹字体中添加您的字体 (app/res/font)。

之后就可以使用textview并设置字体了

<TextView
    android:id="@+id/ID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/YourFont"
    android:text="@string/YourText"
    android:textColor="@color/YourColor"
    android:textSize="20dp" />

在你的风格中,你可以尝试将 "app:fontFamily" 更改为 "android:fontFamily"

希望这会有所帮助

您可以将字体放在资产文件夹中并使用以下代码来完成:

Typeface tf = Typeface.createFromAsset(getAssets(), "your_font.ttf"); yourTextView.setTypeface(tf);

有一个书法图书馆。它用于像您这样的情况 - 替换旧手机上所有视图中的字体。如果我是正确的,它不支持字体资源,只支持普通的 .ttf 文件。参见:https://github.com/chrisjenx/Calligraphy

我正在开发一个支持旧手机字体资源的库。它比 Calligraphy 更干净,但图书馆本身非常大,所以它可能不是最适合你的。字体支持提交被很好地提取,你可以在这里找到它:https://github.com/ZieIony/Carbon/commit/baefcfb1941ecc1b4e293f31f5220ab7abaf4584

答案的本质部分是以下方法。我猜它取自 Material 组件源。您可以将它添加到您的文本字段和按钮以使用它来处理 xml 属性。

private void handleFontAttribute(TypedArray appearance, int textStyle, int attributeId) {
    WeakReference<android.widget.TextView> textViewWeak = new WeakReference<>(this);
    AtomicBoolean asyncFontPending = new AtomicBoolean();
    ResourcesCompat.FontCallback replyCallback = new ResourcesCompat.FontCallback() {
        @Override
        public void onFontRetrieved(@NonNull Typeface typeface) {
            if (asyncFontPending.get()) {
                android.widget.TextView textView = textViewWeak.get();
                if (textView != null)
                    textView.setTypeface(typeface, textStyle);
            }
        }
         @Override
        public void onFontRetrievalFailed(int reason) {
        }
    };
    try {
        int resourceId = appearance.getResourceId(attributeId, 0);
        TypedValue mTypedValue = new TypedValue();
        Typeface typeface = ResourcesCompat.getFont(getContext(), resourceId, mTypedValue, textStyle, replyCallback);
        if (typeface != null) {
            asyncFontPending.set(true);
            setTypeface(typeface, textStyle);
        }
    } catch (UnsupportedOperationException | Resources.NotFoundException ignored) {
    }
}