Customizing Fonts in XML Layouts (Android)
As you have noticed, defining widget fonts in XML layouts is currently not supported in Android. Instead, fonts can only be specified using system-installed ones.
Alternative Solutions
To overcome this limitation, you have a few options:
Custom TextView Extension
To simplify the customization process, consider extending the TextView class as shown below:
TextViewPlus.java:
public class TextViewPlus extends TextView { ... private void setCustomFont(Context ctx, String asset) { Typeface tf = null; try { tf = Typeface.createFromAsset(ctx.getAssets(), asset); } catch (Exception e) { ... } setTypeface(tf); } }
attrs.xml:
<declare-styleable name="TextViewPlus"> <attr name="customFont" format="string"/> </declare-styleable>
main.xml:
<LinearLayout ...> <com.example.TextViewPlus android:customFont="saxmono.ttf" ... /> </LinearLayout>
With this extension, you can specify custom fonts in XML layouts by setting the customFont attribute for each widget. The saxmono.ttf file should be placed in the assets folder.
Important Note
It's worth noting that using this method can lead to memory concerns. See chedabob's comment for more details.
The above is the detailed content of How Can I Customize Fonts in Android XML Layouts?. For more information, please follow other related articles on the PHP Chinese website!