Zoeken…


Een aangepast lettertype in uw app plaatsen

  1. Ga naar de (projectmap)
  2. Vervolgens app -> src -> main.
  3. Maak map 'assets -> fonts' aan in de hoofdmap.
  4. Plaats uw 'fontfile.ttf' in de map met lettertypen.

Een lettertype initialiseren

private Typeface myFont;

// A good practice might be to call this in onCreate() of a custom
// Application class and pass 'this' as Context. Your font will be ready to use
// as long as your app lives
public void initFont(Context context) {
    myFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
}

Een aangepast lettertype gebruiken in een TextView

public void setFont(TextView textView) {
    textView.setTypeface(myFont);    
}

Lettertype toepassen op TextView by xml (niet vereist Java-code)

TextViewPlus.java:

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 typeface = null;
        try {
            typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
        } catch (Exception e) {
            Log.e(TAG, "Unable to load typeface: "+e.getMessage());
            return false;
        }

        setTypeface(typeface);
        return true;
    }
}

attrs.xml: (waar res / waarden worden geplaatst )

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

Hoe te gebruiken:

<?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-auto"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.mypackage.TextViewPlus
        android:id="@+id/textViewPlus1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="@string/showingOffTheNewTypeface"
        foo:customFont="my_font_name_regular.otf">
    </com.mypackage.TextViewPlus>
</LinearLayout>

Aangepast lettertype in canvastekst

Tekst op canvas tekenen met uw lettertype uit elementen.

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/SomeFont.ttf");
Paint textPaint = new Paint();
textPaint.setTypeface(typeface);
canvas.drawText("Your text here", x, y, textPaint);

Efficiënt laden van lettertypen

Het laden van aangepaste lettertypen kan leiden tot slechte prestaties. Ik raad ten zeerste aan om deze kleine helper te gebruiken die je reeds gebruikte lettertypen in een hashtabel opslaat / laadt.

public class TypefaceUtils {

private static final Hashtable<String, Typeface> sTypeFaces = new Hashtable<>();

/**
 * Get typeface by filename from assets main directory
 *
 * @param context
 * @param fileName the name of the font file in the asset main directory
 * @return
 */
public static Typeface getTypeFace(final Context context, final String fileName) {
    Typeface tempTypeface = sTypeFaces.get(fileName);

    if (tempTypeface == null) {
        tempTypeface = Typeface.createFromAsset(context.getAssets(), fileName);
        sTypeFaces.put(fileName, tempTypeface);
    }

    return tempTypeface;
}

}

Gebruik:

Typeface typeface = TypefaceUtils.getTypeface(context, "RobotoSlab-Bold.ttf");
setTypeface(typeface);

Aangepast lettertype voor hele activiteit

public class ReplaceFont {

public static void changeDefaultFont(Context context, String oldFont, String assetsFont) {
    Typeface typeface = Typeface.createFromAsset(context.getAssets(), assetsFont);
    replaceFont(oldFont, typeface);
}

private static void replaceFont(String oldFont, Typeface typeface) {
    try {
        Field myField = Typeface.class.getDeclaredField(oldFont);
        myField.setAccessible(true);
        myField.set(null, typeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

Vervolgens in uw activiteit, in de methode onCreate() :

// Put your font to assets folder...

ReplaceFont.changeDefaultFont(getApplication(), "DEFAULT", "LinLibertine.ttf");

Werken met lettertypen in Android O

Android O verandert de manier om met lettertypen te werken.

Android O introduceert een nieuwe functie, genaamd Lettertypen in XML , waarmee u lettertypen als bronnen kunt gebruiken. Dit betekent dat het niet nodig is om lettertypen als activa te bundelen. Lettertypen worden nu in een R- bestand gecompileerd en zijn automatisch als bron in het systeem beschikbaar.

Om een nieuw lettertype toe te voegen, moet u het volgende doen:

  • Maak een nieuwe bronnenmap: res/font .
  • Voeg uw lettertypebestanden toe aan deze map met lettertypen. Door bijvoorbeeld myfont.ttf toe te myfont.ttf , kunt u dit lettertype gebruiken via R.font.myfont .

U kunt ook uw eigen lettertypefamilie maken door het volgende XML-bestand toe te voegen aan de map res/font :

<?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/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

U kunt zowel het lettertypebestand als het lettertypefamiliebestand op dezelfde manier gebruiken:

  • In een XML-bestand, bijvoorbeeld met het kenmerk android:fontFamily , bijvoorbeeld als volgt:

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/myfont"/>
    

    Of zo:

    <style name="customfontstyle" parent="@android:style/TextAppearance.Small">
        <item name="android:fontFamily">@font/myfont</item>
    </style>
    
  • In uw code , met behulp van de volgende coderegels:

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


Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow