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

Добавление пользовательского шрифта в тему на Android

Есть ли способ добавить пользовательские шрифты в Темы на Android?

Я прочитал Быстрый совет: настройте шрифты Android, но здесь мы должны программно добавить шрифт в текст.

TextView txt = (TextView) findViewById(R.id.custom_font);  
Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");  
txt.setTypeface(font); 

Но я хочу установить пользовательский шрифт по стилю/теме.

4b9b3361

Ответ 1

К сожалению, Android не обеспечивает быстрый, легкий и чистый способ, с помощью которого можно изменить шрифт для всего приложения. Но в последнее время я рассмотрел этот вопрос и создал некоторые инструменты, которые позволяют вам менять шрифт без какого-либо кодирования (вы можете делать все это через xml, стили и даже текст). Они основаны на аналогичных решениях, как вы видите в других ответах здесь, но допускаете гораздо большую гибкость. Вы можете прочитать все об этом на в этом блоге и посмотреть проект github здесь.

Вот пример того, как применять эти инструменты. Поместите все ваши файлы шрифтов в assets/fonts/. Затем объявите эти шрифты в xml файле (например, res/xml/fonts.xml) и загрузите этот файл в начале вашего приложения с помощью TypefaceManager.initialize(this, R.xml.fonts); (например, в классе onCreate вашего приложения). Файл xml выглядит так:

<?xml version="1.0" encoding="utf-8"?>
<familyset>

    <!-- Some Font. Can be referenced with 'someFont' or 'aspergit' -->
    <family>
        <nameset>
            <name>aspergit</name>
            <name>someFont</name>
        </nameset>
        <fileset>
            <file>Aspergit.ttf</file>
            <file>Aspergit Bold.ttf</file>
            <file>Aspergit Italic.ttf</file>
            <file>Aspergit Bold Italic.ttf</file>
        </fileset>
    </family>

    <!-- Another Font. Can be referenced with 'anotherFont' or 'bodoni' -->
    <family>
        <nameset>
            <name>bodoni</name>
            <name>anotherFont</name>
        </nameset>
        <fileset>
            <file>BodoniFLF-Roman.ttf</file>
            <file>BodoniFLF-Bold.ttf</file>
        </fileset>
    </family>

</familyset>

Теперь вы можете использовать эти шрифты в своем стиле или xml (при использовании инструментов, упомянутых выше), установив атрибут flFont в пользовательский TextView com.innovattic.font.FontTextView в вашем макете xml. Ниже вы можете увидеть, как вы можете применить шрифт ко всем текстам всего вашего приложения, просто отредактировав res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <!-- Application theme -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:textViewStyle">@style/MyTextViewStyle</item>
    </style>

    <!-- Style to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextViewStyle" parent="@android:style/Widget.Holo.Light.TextView">
        <item name="android:textAppearance">@style/MyTextAppearance</item>
    </style>

    <!-- Text appearance to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextAppearance" parent="@android:style/TextAppearance.Holo">
        <!-- Alternatively, reference this font with the name "aspergit" -->
        <!-- Note that only our own TextView will use the font attribute -->
        <item name="flFont">someFont</item>
        <item name="android:textStyle">bold|italic</item>
    </style>

    <!-- Alternative style, maybe for some other widget -->
    <style name="StylishFont">
        <item name="flFont">anotherFont</item>
        <item name="android:textStyle">normal</item>
    </style>

</resources>

С прилагаемым res/layout/layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <!-- This text view is styled with the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This uses my font in bold italic style" />

    <!-- This text view is styled here and overrides the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:flFont="anotherFont"
        android:textStyle="normal"
        android:text="This uses another font in normal style" />

    <!-- This text view is styled with a style and overrides the app theme -->
    <com.innovattic.font.FontTextView
        style="@style/StylishFont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This also uses another font in normal style" />

</LinearLayout>

Не забудьте применить тему в манифесте Android.

Ответ 2

Я думаю, что это дубликат этого вопроса и этот.

В моих действиях во время выполнения я использую что-то вроде этого:

FontUtils.setCustomFont(findViewById(R.id.top_view), getAssets());

В XML:

        <TextView
            android:id="@+id/my_label"
            android:tag="condensed"
            android:text="@string/label"
            ... />

Итак, теоретически вы можете создать стиль и использовать его вместе с FontUtils/runtime code.

<style name="roboto_condensed">
    <item name="android:tag">condensed,your-own-css-like-language-here</item>
</style>

Класс FontUtils:

public class FontUtils {
  private static Typeface normal;

  private static Typeface bold;

  private static Typeface condensed;

  private static Typeface light;

  private static void processsViewGroup(ViewGroup v, final int len) {

    for (int i = 0; i < len; i++) {
      final View c = v.getChildAt(i);
      if (c instanceof TextView) {
        setCustomFont((TextView) c);
      } else if (c instanceof ViewGroup) {
        setCustomFont((ViewGroup) c);
      }
    }
  }

  private static void setCustomFont(TextView c) {
    Object tag = c.getTag();
    if (tag instanceof String) {
      if (((String) tag).contains("bold")) {
        c.setTypeface(bold);
        return;
      }
      if (((String) tag).contains("condensed")) {
        c.setTypeface(condensed);
        return;
      }
      if (((String) tag).contains("light")) {
        c.setTypeface(light);
        return;
      }
    }
    c.setTypeface(normal);
  }

  public static void setCustomFont(View topView, AssetManager assetsManager) {
    if (normal == null || bold == null || condensed == null || light == null) {
      normal = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Regular.ttf");
      bold = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Bold.ttf");
      condensed = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Condensed.ttf");
      light = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Light.ttf");
    }

    if (topView instanceof ViewGroup) {
      setCustomFont((ViewGroup) topView);
    } else if (topView instanceof TextView) {
      setCustomFont((TextView) topView);
    }
  }

  private static void setCustomFont(ViewGroup v) {
    final int len = v.getChildCount();
    processsViewGroup(v, len);
  }
}

Ответ 3

Используя мой CustomTextView, вы указываете имя файла шрифта в своей папке assets непосредственно в вашем файле макета XML.

Мой ответ здесь

Ответ 4

Вы можете указать свой собственный тип шрифта в папке с ресурсами и оттуда оттуда.

Объявите шрифты как:

Typeface helveticaBold;
Typeface helveticaRegular;

в onCreate() напишите следующий код:

helveticaBold = Typeface.createFromAsset(getAssets(), "helvetica_bold.ttf");
helveticaRegular = Typeface.createFromAsset(getAssets(), "helvetica_regular.ttf");

Наконец, установите шрифт текста TextView или EditText как:

editText.setTypeface(helveticaRegular);

что он...

Ответ 5

Я думаю, что ответом на ваш вопрос будет пользовательский TextView с дополнительным параметром XML, который вы можете включить в свои темы.

Вы можете проанализировать это значение в конструкторе TextView (контекст контекста, AttributeSet attrs) для его инициализации. Проверьте эту ссылку, например, на определение пользовательских атрибутов для ваших просмотров и их инициализацию.

Ответ 6

Надеюсь, это то, что вы имели в виду, но если это не так, это должно быть хорошей ссылкой для других.

** Примечание. Шрифты можно найти. Компьютер/локальный диск (C:)/Windows/Fonts **

Скопируйте шрифт, который вы хотите использовать в папке Fonts выше, и вставьте его во вновь созданную папку в папке с ресурсами в Eclipse.

    private void initTypeFace()
    {
        TypeFace tf = TypeFace.createFromAsset(getAsset(),
                      "Chantelli Antiqua.ttf");

        TextView txt = (TextView) findViewById(R.id.custom_font);

        txt.setTypeface(tf);
        example_button1.setTypeface(tf);
        example_button2.setTypeface(tf);
    }