Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is a fairly easy way to do this via XML. You just need to create your own widget that extends TextView.</p> <p>First, create a file in res/values/attrs.xml with the following content:</p> <pre><code>&lt;resources&gt; &lt;declare-styleable name="TypefacedTextView"&gt; &lt;attr name="typeface" format="string" /&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre> <p>After that, create your custom widget:</p> <pre><code>package your.package.widget; public class TypefacedTextView extends TextView { public TypefacedTextView(Context context, AttributeSet attrs) { super(context, attrs); //Typeface.createFromAsset doesn't work in the layout editor. Skipping... if (isInEditMode()) { return; } TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView); String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface); styledAttrs.recycle(); if (fontName != null) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName); setTypeface(typeface); } } } </code></pre> <p>As you can see, the code above will read a font inside the assets/ folder. For this example, I am assuming that there is a file called "custom.ttf" in the assets folder. At last, use the widget in the XMLs:</p> <pre><code>&lt;your.package.widget.TypefacedTextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:your_namespace="http://schemas.android.com/apk/res/your.package" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Custom fonts in XML are easy" android:textColor="#FFF" android:textSize="14dip" your_namespace:typeface="custom.ttf" /&gt; </code></pre> <p>Note: you won't be able to see your custom font in Eclipse's layout editor. This is why I put the <code>isInEditMode()</code> check. But if you run your app, the custom font will work like a charm.</p> <p>Hope it helps!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload