Страницы

Поиск по вопросам

суббота, 28 декабря 2019 г.

Как задать в приложении свой шрифт?

#android #android_studio #шрифты #textview


Как добавить в приложение свой шрифт и присвоить элементу TextView?
    


Ответы

Ответ 1



Краткий вариант TextView textView = (TextView) findViewById(); Typeface typeFace = Typeface.createFromAsset(getAssets(), ""); textView.setTypeface(typeFace); Но лучше (ну, просто кто-то любит более полные решения и не любит копировать одно и то же для всех 128 TexView в приложении) отнаследоваться от TextView: com/example/foo/view/FontableTextView.java public class FontableTextView extends TextView { public FontableTextView(Context context) { super(context); } public FontableTextView(Context context, AttributeSet attrs) { super(context, attrs); UiUtil.setCustomFont(this, context, attrs, R.styleable.com_example_foo_view_FontableTextView, R.styleable.com_example_foo_view_FontableTextView_font); } public FontableTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); UiUtil.setCustomFont(this, context, attrs, R.styleable.com_example_foo_view_FontableTextView, R.styleable.com_example_foo_view_FontableTextView_font); } } res/values/attr.xml ... res/layuot/main_activity.xml ... ... com/example/foo/utils/UiUtil.java public class UiUtil { public static final String TAG = "UiUtil"; public static void setCustomFont(View textViewOrButton, Context ctx, AttributeSet attrs, int[] attributeSet, int fontId) { TypedArray a = ctx.obtainStyledAttributes(attrs, attributeSet); String customFont = a.getString(fontId); setCustomFont(textViewOrButton, ctx, customFont); a.recycle(); } private static boolean setCustomFont(View textView, Context ctx, String asset) { if (TextUtils.isEmpty(asset)) return false; Typeface tf = null; try { tf = getFont(ctx, asset); if (textView instanceof TextView) { ((TextView) textView).setTypeface(tf); } } catch (Exception e) { Log.e(TAG, "Could not get typeface: " + asset, e); return false; } return true; } private static final Hashtable> fontCache = new Hashtable>(); public static Typeface getFont(Context c, String name) { synchronized (fontCache) { if (fontCache.get(name) != null) { SoftReference ref = fontCache.get(name); if (ref.get() != null) { return ref.get(); } } Typeface typeface = Typeface.createFromAsset( c.getAssets(), "fonts/" + name ); fontCache.put(name, new SoftReference(typeface)); return typeface; } } } Сам шрифт положить в assets/fonts, в частности: assets/fonts/coolfont.ttf

Ответ 2



Typeface.createFromAsset textView.setTypeface(typeFace)

Комментариев нет:

Отправить комментарий