Добавление пользовательских шрифтов для Android API 14 - PullRequest
0 голосов
/ 05 декабря 2018

Ошибка
Ошибка: атрибут стиля 'app: attr / fontFamily' не найден.Сообщение {kind = ERROR, text = error: атрибут стиля '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>

Я добавил raleway_medium.ttf в app / assets / font / raleway_medium.ttf

Ответы [ 3 ]

0 голосов
/ 05 декабря 2018

Вы можете сделать это, поместив свой шрифт в папку ресурсов и используя следующий код:

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

0 голосов
/ 05 декабря 2018

Есть библиотека под названием Каллиграфия.Он используется в таких случаях, как ваш - для замены шрифтов во всех видах на старых телефонах.Если я прав, он не поддерживает шрифтовые ресурсы, а просто файлы .ttf.См .: https://github.com/chrisjenx/Calligraphy

Я работаю над библиотекой с поддержкой ресурсов шрифтов для старых телефонов.Он работает чище, чем Каллиграфия, но сама библиотека очень большая, поэтому она может не подойти для вас.Фиксация поддержки шрифтов хорошо извлечена, и вы можете найти ее здесь: https://github.com/ZieIony/Carbon/commit/baefcfb1941ecc1b4e293f31f5220ab7abaf4584

И основная часть ответа - следующий метод.Я думаю, это было взято из источников компонентов материалов.Вы можете добавить его в свои текстовые поля и кнопки, чтобы использовать его для обработки атрибута 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) {
    }
}
0 голосов
/ 05 декабря 2018

Добавьте ваш шрифт в вашу папку font (app / res / font).

После этого вы можете использовать текстовое представление и установить шрифт

<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"

Надеюсь, это поможет

...