Подтвердить что ты не робот

Задайте конкретный шрифт в файле styles.xml

Я определяю стиль XML для моего приложения для Android. У меня есть некоторые файлы TTF, которые я хочу использовать, как я могу установить шрифт для использования этих файлов в качестве шрифта в отличие от общих "sans", "serif" и "monospace". Благодаря

4b9b3361

Ответ 1

Вы можете использовать только пользовательские шрифты с помощью кода Java, а не через XML или стили оформления - извините!

Ответ 2

TextViewPlus.java:

package com.example;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TextViewPlus extends TextView {
    private static final String TAG = "TextView";

    public TextViewPlus(Context context) {
        super(context);
    }

    public TextViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
        tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface: "+e.getMessage());
            return false;
        }

        setTypeface(tf);  
        return true;
    }

}

attrs.xml: (в res/values)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextViewPlus">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res/com.example"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.example.TextViewPlus
        android:id="@+id/textViewPlus1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="@string/showingOffTheNewTypeface"
        foo:customFont="saxmono.ttf">
    </com.example.TextViewPlus>
</LinearLayout>

Вы должны поместить "saxmono.ttf" в папку с ресурсами.

Ответ 3

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style>
</resources>

Ответ 4

Да, ты можешь :)

Шаг 1. Создайте папку, назовите ее "шрифт" и поместите в нее свой файл .ttf. Step one

Шаг 2: Перейдите в style.xml и сделайте следующее: - step two

Шаг 3. Используйте тег стиля в любом месте представления (TextView, TabLayout и т.д.): -

Step three

Ответ 6

enter image description here

Создайте каталог шрифтов в папке ресурсов и вставьте файл шрифта ttf. Затем создайте ресурс шрифта XML и вставьте следующие строки.

    <?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/roboto_light" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/roboto_light_italic" />

</font-family>

Теперь вы можете применить шрифт, как показано ниже. Также обратите внимание на атрибут 'textStyle'

  <TextView
                    android:textStyle="italic"
                    android:fontFamily="@font/family_roboto_light"
                    android:textColor="@color/primaryTextColor"
                    android:textSize="20sp"
                    android:gravity="center"
                    android:id="@+id/textView36"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="No Internet connection" />

  <TextView
                    android:fontFamily="@font/family_roboto_light"
                    android:textStyle="normal"
                    android:textSize="20sp"
                    android:gravity="center"
                    android:id="@+id/textView37"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="No Internet connection" />

Если вы хотите сделать из кода, используйте следующий, но минимальный уровень API 26

Typeface typeface = getResources().getFont(R.font. roboto_light_italic);
textView.setTypeface(typeface);

Библиотека поддержки 26.0 обеспечивает поддержку функции "Шрифты в XML" на устройствах под управлением Android 4.1 (уровень API 16) и выше.

Typeface typeface = ResourcesCompat.getFont(context, R.font. roboto_light_italic);

Ответ 7

см. APIDemos Пример в документации.