This question has already been answered:

How to change the font header for the activity in the android?

Reported as a duplicate by participants of Kirill Stoianov , Denis , αλεχολυτ , Streletz , cheops 25 Sep '16 at 20:35 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

And not even one way.

The first one is to connect your custom font, and it is done like this:

String custom_font = "fonts/custom_font.ttf"; Typeface CF = Typeface.createFromAsset(getAssets(), custom_font); ((TextView) findViewById(R.id.sometextview)).setTypeface(CF); 

But if you have a lot of TextView elements, then you have to write a font connection for each of them, which is a lot of extra code.

Therefore, the attention of the second solution, namely to inherit from 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; } 

Attributes file: attrs.xml (res / values)

 <resources> <declare-styleable name="TextViewPlus"> <attr name="customFont" format="string"/> </declare-styleable> 

Well, actually your file activity_main.xml

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

Do not forget to put the font file saxmono.tt in the assets folder.

  • And you forgot to cache downloaded fonts. And it is fatal. - Yura Ivanov
  • I do not see your edit, dare) - Morozov
  • one
    see the comment to the question. and your answer will lead to.stackoverflow.com/questions/497113 - Yura Ivanov