Как изменить шрифт в TextView? - PullRequest
278 голосов
/ 22 мая 2010

Как изменить шрифт в TextView, по умолчанию он отображается как Arial? Как изменить его на Helvetica?

Ответы [ 16 ]

4 голосов
/ 28 августа 2013
import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Typeface;

public class FontsManager {

    private static FontsManager instance;

    private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();

    private static Context context;

    private FontsManager(final Context ctx) {
        if (context == null) {
            context = ctx;
        }
    }

    public static FontsManager getInstance(final Context appContext) {
        if (instance == null) {
            instance = new FontsManager(appContext);
        }
        return instance;
    }

    public static FontsManager getInstance() {
        if (instance == null) {
            throw new RuntimeException(
                    "Call getInstance(Context context) at least once to init the singleton properly");
        }
        return instance;
    }

    public Typeface getFont(final String assetName) {
        final WeakReference<Typeface> tfReference = typefaces.get(assetName);
        if (tfReference == null || tfReference.get() == null) {
            final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
                    assetName);
            typefaces.put(assetName, new WeakReference<Typeface>(tf));
            return tf;
        }
        return tfReference.get();
    }

}

Таким образом, вы можете создать View, который наследуется от TextView и вызывает setTypeface для своего конструктора.

2 голосов
/ 30 ноября 2016
  1. добавить класс FontTextView.java:

public class FontTextView extends TextView {
    String fonts[] = {"HelveticaNeue.ttf", "HelveticaNeueLight.ttf", "motschcc.ttf", "symbol.ttf"};

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode()) {
            init(attrs);
        }

    }

    public FontTextView(Context context) {
        super(context);
        if (!isInEditMode()) {
            init(null);
        }
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
            if (a.getString(R.styleable.FontTextView_font_type) != null) {
                String fontName = fonts[Integer.valueOf(a.getString(R.styleable.FontTextView_font_type))];

                if (fontName != null) {
                    Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/" + fontName);
                    setTypeface(myTypeface);
                }
                a.recycle();
            }
        }
    }
}

добавить в библиотеку ресурсов шрифт
enter image description here

добавить в attrs.xml, числа должны быть в порядке в классе массива.

<declare-styleable name="FontTextView">
<attr name="font_type" format="enum">
    <enum name="HelveticaNeue" value="0"/>
    <enum name="HelveticaNeueLight" value="1"/>
    <enum name="motschcc" value="2"/>
    <enum name="symbol" value="3"/>
</attr>


Выберите шрифт из списка
enter image description here
2 голосов
/ 22 января 2014

получить шрифт из ресурса и установить для всех дочерних элементов

public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"));// "BKOODB.TTF"));
        }
    } catch (Exception e) {
 }
 } 
0 голосов
/ 03 июля 2018

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

Проверьте ссылку ниже, чтобы проверить шрифты робота:

Как использовать Roboto в XML-макете

Возвращаясь к вашему вопросу, если вы хотите изменить шрифт для всех TextView / Button в вашем приложении , попробуйте добавить приведенный ниже код в ваш файл styles.xml для использования Roboto-light шрифт:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

И не забудьте использовать AppTheme в вашем AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>
0 голосов
/ 13 февраля 2018

Когда ваш шрифт хранится внутри res/asset/fonts/Helvetica.ttf, используйте следующее:

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf"); 
txt.setTypeface(tf);

Или, если ваш файл шрифтов хранится внутри res/font/helvetica.ttf, используйте следующее:

Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
0 голосов
/ 02 августа 2016

Может быть, что-то немного проще:

public class Fonts {
  public static HashSet<String,Typeface> fonts = new HashSet<>();

  public static Typeface get(Context context, String file) {
    if (! fonts.contains(file)) {
      synchronized (this) {
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
        fonts.put(name, typeface);
      }
    }
    return fonts.get(file);
  }
}

// Usage
Typeface myFont = Fonts.get("arial.ttf");

(Обратите внимание, что этот код не проверен, но в целом этот подход должен работать хорошо.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...