Android:要为整个应用程序设置自定义字体,而不是运行时
是否可以在应用程序的每个控件中设置任何自定义字体? 而不一定是运行时? (即如果可能的话从xml或者只在JAVA文件中的整个应用程序一次)
我可以从这个代码设置一个控件的字体。
public static void setFont(TextView textView) { Typeface tf = Typeface.createFromAsset(textView.getContext() .getAssets(), "fonts/BPreplay.otf"); textView.setTypeface(tf); }
而这个代码的问题是应该为每个控件调用。 我想调用这个或任何类似的方法一次,或者如果可能的话在xml中设置属性。 可能吗?
编辑 :所以这是一段时间,我想补充我认为是最好的方式来做到这一点,并通过XML不低于!
所以首先,你要创build一个覆盖你想要自定义的View的新类。 (例如想要一个自定义字体的Button
?扩展Button
)。 举个例子吧:
public class CustomButton extends Button { private final static int ROBOTO = 0; private final static int ROBOTO_CONDENSED = 1; public CustomButton(Context context) { super(context); } public CustomButton(Context context, AttributeSet attrs) { super(context, attrs); parseAttributes(context, attrs); //I'll explain this method later } public CustomButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); } }
现在,如果没有,请在res/values/attrs.xml
下添加一个XML文档,然后添加:
<resources> <!-- Define the values for the attribute --> <attr name="typeface" format="enum"> <enum name="roboto" value="0"/> <enum name="robotoCondensed" value="1"/> </attr> <!-- Tell Android that the class "CustomButton" can be styled, and which attributes it supports --> <declare-styleable name="CustomButton"> <attr name="typeface"/> </declare-styleable> </resources>
好的,那么,就让我们回到之前的parseAttributes()
方法:
private void parseAttributes(Context context, AttributeSet attrs) { TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.CustomButton); //The value 0 is a default, but shouldn't ever be used since the attr is an enum int typeface = values.getInt(R.styleable.CustomButton_typeface, 0); switch(typeface) { case ROBOTO: default: //You can instantiate your typeface anywhere, I would suggest as a //singleton somewhere to avoid unnecessary copies setTypeface(roboto); break; case ROBOTO_CONDENSED: setTypeface(robotoCondensed); break; } values.recycle(); }
现在你全都定了 你可以为任何东西添加更多的属性(你可以添加另一个typefaceStyle – 粗体,斜体等),但现在让我们看看如何使用它:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res/com.yourpackage.name" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.yourpackage.name.CustomButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me!" custom:typeface="roboto" /> </LinearLayout>
xmlns:custom
行真的可以是任何东西,但约定是上面显示的。 重要的是它是唯一的,这就是使用包名称的原因。 现在,您只需使用custom:
前缀为您的属性, android:
前缀为android属性。
最后一件事:如果你想在样式( res/values/styles.xml
)中使用它,你不应该添加xmlns:custom
行。 只需引用没有前缀的属性的名称即可:
<style name="MyStyle> <item name="typeface">roboto</item> </style>
(PREVIOUS ANSWER)
在Android中使用自定义字体
这应该有所帮助。 基本上,在XML中没有办法做到这一点,就我所知,在代码中没有更简单的方法。 你总是可以有一个setLayoutFont()方法来创build一次字体,然后为每个字体运行setTypeface()。 每次将新项目添加到布局时,您都必须更新它。 如下所示:
public void setLayoutFont() { Typeface tf = Typeface.createFromAsset( getBaseContext().getAssets(), "fonts/BPreplay.otf"); TextView tv1 = (TextView)findViewById(R.id.tv1); tv1.setTypeface(tf); TextView tv2 = (TextView)findViewById(R.id.tv2); tv2.setTypeface(tf); TextView tv3 = (TextView)findViewById(R.id.tv3); tv3.setTypeface(tf); }
编辑 :所以我刚刚实现这样的事情自己,我怎么最终这样做是这样的function:
public static void setLayoutFont(Typeface tf, TextView...params) { for (TextView tv : params) { tv.setTypeface(tf); } }
然后,从onCreate()中使用这个方法,并传递所有你想要更新的TextView:
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/BPreplay.otf"); //find views by id... setLayoutFont(tf, tv1, tv2, tv3, tv4, tv5);
编辑9/5/12:
因此,由于这仍然得到意见和投票,我想添加一个更好,更完整的方法:
Typeface mFont = Typeface.createFromAsset(getAssets(), "fonts/BPreplay.otf"); ViewGroup root = (ViewGroup)findViewById(R.id.myrootlayout); setFont(root, mFont); /* * Sets the font on all TextViews in the ViewGroup. Searches * recursively for all inner ViewGroups as well. Just add a * check for any other views you want to set as well (EditText, * etc.) */ public void setFont(ViewGroup group, Typeface font) { int count = group.getChildCount(); View v; for(int i = 0; i < count; i++) { v = group.getChildAt(i); if(v instanceof TextView || v instanceof Button /*etc.*/) ((TextView)v).setTypeface(font); else if(v instanceof ViewGroup) setFont((ViewGroup)v, font); } }
如果您将布局的根传递给布局,那么它将以recursion方式检查该布局中的TextView
或Button
视图(或者添加到if语句的任何其他视图),并设置字体而不必通过ID指定它们。 这当然是假设你想把字体设置为每个视图。
有一个相当简单的方法来通过XML来做到这一点。 您只需要创build自己的扩展TextView的小部件。
首先,在res / values / attrs.xml中使用以下内容创build一个文件:
<resources> <declare-styleable name="TypefacedTextView"> <attr name="typeface" format="string" /> </declare-styleable> </resources>
之后,创build您的自定义小部件:
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); } } }
正如你所看到的,上面的代码将读取资产/文件夹内的字体。 对于这个例子,我假定资产文件夹中有一个名为“custom.ttf”的文件。 最后,在XML中使用小部件:
<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" />
注意:您将无法在Eclipse的布局编辑器中看到自定义字体。 这就是为什么我把isInEditMode()
检查。 但是,如果你运行你的应用程序,自定义字体将像魅力一样工作。
希望它有帮助!
带有roboto字体的TextView示例:
attr.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RobotoTextView"> <attr name="typeface"/> </declare-styleable> <attr name="typeface" format="enum"> <enum name="roboto_thin" value="0"/> <enum name="roboto_thin_italic" value="1"/> <enum name="roboto_light" value="2"/> <enum name="roboto_light_italic" value="3"/> <enum name="roboto_regular" value="4"/> <enum name="roboto_italic" value="5"/> <enum name="roboto_medium" value="6"/> <enum name="roboto_medium_italic" value="7"/> <enum name="roboto_bold" value="8"/> <enum name="roboto_bold_italic" value="9"/> <enum name="roboto_black" value="10"/> <enum name="roboto_black_italic" value="11"/> <enum name="roboto_condensed" value="12"/> <enum name="roboto_condensed_italic" value="13"/> <enum name="roboto_condensed_bold" value="14"/> <enum name="roboto_condensed_bold_italic" value="15"/> </attr> </resources>
RobotoTextView.java:
public class RobotoTextView extends TextView { /* * Permissible values for the "typeface" attribute. */ private final static int ROBOTO_THIN = 0; private final static int ROBOTO_THIN_ITALIC = 1; private final static int ROBOTO_LIGHT = 2; private final static int ROBOTO_LIGHT_ITALIC = 3; private final static int ROBOTO_REGULAR = 4; private final static int ROBOTO_ITALIC = 5; private final static int ROBOTO_MEDIUM = 6; private final static int ROBOTO_MEDIUM_ITALIC = 7; private final static int ROBOTO_BOLD = 8; private final static int ROBOTO_BOLD_ITALIC = 9; private final static int ROBOTO_BLACK = 10; private final static int ROBOTO_BLACK_ITALIC = 11; private final static int ROBOTO_CONDENSED = 12; private final static int ROBOTO_CONDENSED_ITALIC = 13; private final static int ROBOTO_CONDENSED_BOLD = 14; private final static int ROBOTO_CONDENSED_BOLD_ITALIC = 15; /** * List of created typefaces for later reused. */ private final static SparseArray<Typeface> mTypefaces = new SparseArray<Typeface>(16); /** * Simple constructor to use when creating a view from code. * * @param context The Context the view is running in, through which it can * access the current theme, resources, etc. */ public RobotoTextView(Context context) { super(context); } /** * Constructor that is called when inflating a view from XML. This is called * when a view is being constructed from an XML file, supplying attributes * that were specified in the XML file. This version uses a default style of * 0, so the only attribute values applied are those in the Context's Theme * and the given AttributeSet. * <p/> * <p/> * The method onFinishInflate() will be called after all children have been * added. * * @param context The Context the view is running in, through which it can * access the current theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. * @see #RobotoTextView(Context, AttributeSet, int) */ public RobotoTextView(Context context, AttributeSet attrs) { super(context, attrs); parseAttributes(context, attrs); } /** * Perform inflation from XML and apply a class-specific base style. This * constructor of View allows subclasses to use their own base style when * they are inflating. * * @param context The Context the view is running in, through which it can * access the current theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. * @param defStyle The default style to apply to this view. If 0, no style * will be applied (beyond what is included in the theme). This may * either be an attribute resource, whose value will be retrieved * from the current theme, or an explicit style resource. * @see #RobotoTextView(Context, AttributeSet) */ public RobotoTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); } /** * Parse the attributes. * * @param context The Context the view is running in, through which it can access the current theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. */ private void parseAttributes(Context context, AttributeSet attrs) { TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView); int typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0); values.recycle(); setTypeface(obtaintTypeface(context, typefaceValue)); } /** * Obtain typeface. * * @param context The Context the view is running in, through which it can * access the current theme, resources, etc. * @param typefaceValue values for the "typeface" attribute * @return Roboto {@link Typeface} * @throws IllegalArgumentException if unknown `typeface` attribute value. */ private Typeface obtaintTypeface(Context context, int typefaceValue) throws IllegalArgumentException { Typeface typeface = mTypefaces.get(typefaceValue); if (typeface == null) { typeface = createTypeface(context, typefaceValue); mTypefaces.put(typefaceValue, typeface); } return typeface; } /** * Create typeface from assets. * * @param context The Context the view is running in, through which it can * access the current theme, resources, etc. * @param typefaceValue values for the "typeface" attribute * @return Roboto {@link Typeface} * @throws IllegalArgumentException if unknown `typeface` attribute value. */ private Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException { Typeface typeface; switch (typefaceValue) { case ROBOTO_THIN: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Thin.ttf"); break; case ROBOTO_THIN_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-ThinItalic.ttf"); break; case ROBOTO_LIGHT: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); break; case ROBOTO_LIGHT_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-LightItalic.ttf"); break; case ROBOTO_REGULAR: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf"); break; case ROBOTO_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Italic.ttf"); break; case ROBOTO_MEDIUM: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); break; case ROBOTO_MEDIUM_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-MediumItalic.ttf"); break; case ROBOTO_BOLD: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf"); break; case ROBOTO_BOLD_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BoldItalic.ttf"); break; case ROBOTO_BLACK: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Black.ttf"); break; case ROBOTO_BLACK_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BlackItalic.ttf"); break; case ROBOTO_CONDENSED: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Condensed.ttf"); break; case ROBOTO_CONDENSED_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-CondensedItalic.ttf"); break; case ROBOTO_CONDENSED_BOLD: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BoldCondensed.ttf"); break; case ROBOTO_CONDENSED_BOLD_ITALIC: typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BoldCondensedItalic.ttf"); break; default: throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue); } return typeface; } }
使用示例:
<your.package.widget.RobotoTextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:typeface="roboto_thin" android:textSize="22sp" android:text="Roboto Thin"/>
资源: Roboto&Noto字体
这太晚了,但我帮助其他人
我已经创build了CustomTextView,它有一个名为typeFace的属性,它关心内存泄漏问题与字体加载没有caching
首先是一次只能从资产中加载字体的Fonts
类
import android.content.Context; import android.graphics.Typeface; import java.util.Hashtable; /** * Created by tonyhaddad on 7/19/15. */ public class Fonts { private Context context; public Fonts(Context context) { this.context = context; } private static Hashtable<String, Typeface> sTypeFaces = new Hashtable<String, Typeface>( 4); public static Typeface getTypeFace(Context context, String fileName) { Typeface tempTypeface = sTypeFaces.get(fileName); if (tempTypeface == null) { String fontPath=null; if(fileName=="metabold") fontPath ="fonts/Meta-Bold.ttf"; else if(fileName=="metanormal") fontPath="fonts/Meta-Normal.ttf"; else if(fileName=="gsligh") fontPath="fonts/gesslight.ttf"; else if(fileName=="bold") fontPath="fonts/Lato-Bold.ttf"; else if(fileName=="rcr") fontPath="fonts/RobotoCondensed-Regular.ttf"; else if(fileName=="mpr") fontPath="fonts/MyriadPro-Regular.otf"; else if(fileName=="rr") fontPath="fonts/Roboto-Regular.ttf"; tempTypeface = Typeface.createFromAsset(context.getAssets(), fontPath); sTypeFaces.put(fileName, tempTypeface); } return tempTypeface; } }
那么你需要在attrs.xml中添加一个自定义属性添加这个
<declare-styleable name="CustomFontTextView"> <attr name="typeFace" format="string" /> </declare-styleable>
然后自定义类
package package_name; /** * Created by tonyhaddad on 8/26/15. */ import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; import package_name.R; public class CustomFontTextView extends TextView { String typeFace; public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (isInEditMode()) { return; } TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CustomFontTextView, 0, 0); try { typeFace = a.getString(0); } finally { a.recycle(); } if(typeFace!=null && !typeFace.equalsIgnoreCase("")) { Typeface tf = Fonts.getTypeFace(context, typeFace); setTypeface(tf); } init(); } public CustomFontTextView(Context context, AttributeSet attrs) { super(context, attrs); if (isInEditMode()) { return; } TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CustomFontTextView, 0, 0); try { typeFace = a.getString(0); } finally { a.recycle(); } if(typeFace!=null && !typeFace.equalsIgnoreCase("")) { Typeface tf = Fonts.getTypeFace(context, typeFace); setTypeface(tf); } init(); } public CustomFontTextView(Context context) { super(context); if(typeFace!=null && !typeFace.equalsIgnoreCase("")) { Typeface tf = Fonts.getTypeFace(context, typeFace); setTypeface(tf); } init(); } private void init() { } public String getTypeFace() { return typeFace; } public void setTypeFace(String typeFace) { this.typeFace = typeFace; invalidate(); requestLayout(); } }
最后添加文本视图
<package_name.CustomFontTextView xmlns:custom="http://schemas.android.com/apk/res-auto/package_name" android:id="@+id/txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="41dp" android:gravity="center_vertical" android:text="text" android:textColor="#000" android:textSize="23sp" custom:typeFace="metanormal"/>
你可以用setTypeFace方法改变字体大小
如果您想在此视图中使用多个自定义名称空间,也可以将自定义名称空间移动到您的父级布局
快乐编码:)
下面的方法,在onCreate()中调用并传递给最外层的ViewGroup,除了dynamic创build的文本(即dynamic列表,警报等)以外,其他方法都可以工作。 获取最外层的ViewGroup的简单方法是在任何一个视图上使用getRootView。
public void onCreate(Bundle savedInstanceState){ //onCreate code... EditText text = (EditText) findViewById(R.id.editText1); setTypeFaceForViewGroup((ViewGroup) text.getRootView()); } private void setTypeFaceForViewGroup(ViewGroup vg){ for (int i = 0; i < vg.getChildCount(); i++) { if (vg.getChildAt(i) instanceof ViewGroup) setTypeFaceForViewGroup((ViewGroup) vg.getChildAt(i)); else if (vg.getChildAt(i) instanceof TextView) ((TextView) vg.getChildAt(i)).setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Your_Font.ttf")); } }
这也适用于dynamic内容,你只需要调用它,传入你创build的任何东西,然后创build它(我还没有testing过)。
为了节省内存,你可能需要将字体变成一个静态variables,而不是像我这样在循环运行时创build一个新字体。
如果您正在寻找更通用的编程解决scheme,我创build了一个静态类,可用于设置整个视图的字体(活动UI)。 请注意,我正在使用Mono(C#),但可以使用Java轻松实现它。
您可以将这个类传递给您想要自定义的布局或特定的视图。 如果你想超级高效,你可以使用Singleton模式来实现它。
public static class AndroidTypefaceUtility { static AndroidTypefaceUtility() { } //Refer to the code block beneath this one, to see how to create a typeface. public static void SetTypefaceOfView(View view, Typeface customTypeface) { if (customTypeface != null && view != null) { try { if (view is TextView) (view as TextView).Typeface = customTypeface; else if (view is Button) (view as Button).Typeface = customTypeface; else if (view is EditText) (view as EditText).Typeface = customTypeface; else if (view is ViewGroup) SetTypefaceOfViewGroup((view as ViewGroup), customTypeface); else Console.Error.WriteLine("AndroidTypefaceUtility: {0} is type of {1} and does not have a typeface property", view.Id, typeof(View)); } catch (Exception ex) { Console.Error.WriteLine("AndroidTypefaceUtility threw:\n{0}\n{1}", ex.GetType(), ex.StackTrace); throw ex; } } else { Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / view parameter should not be null"); } } public static void SetTypefaceOfViewGroup(ViewGroup layout, Typeface customTypeface) { if (customTypeface != null && layout != null) { for (int i = 0; i < layout.ChildCount; i++) { SetTypefaceOfView(layout.GetChildAt(i), customTypeface); } } else { Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / layout parameter should not be null"); } } }
在你的活动中,你将需要创build一个Typeface对象。 我使用放在我的资源/资产/目录中的.ttf文件在OnCreate()中创build我的。 确保该文件的属性中标记为Android资产。
protected override void OnCreate(Bundle bundle) { ... LinearLayout rootLayout = (LinearLayout)FindViewById<LinearLayout>(Resource.Id.signInView_LinearLayout); Typeface allerTypeface = Typeface.CreateFromAsset(base.Assets,"Aller_Rg.ttf"); AndroidTypefaceUtility.SetTypefaceOfViewGroup(rootLayout, allerTypeface); }
我想添加一个说明leocadiotine
伟大的解决scheme。 这是完美的,但是当使用这个自定义TextView很多时候减慢了应用程序的速度,因为每次创build一个文本视图时都必须访问资源。 我build议在Adapters
使用类似View Holder pattern
东西,我写了一个例子:
public class Fonts { private static final Map<String, Typeface> typefaces = new HashMap<String, Typeface>(); public static Typeface getTypeface(Context ctx, String fontName) { Typeface typeface = typefaces.get(fontName); if (typeface == null) { typeface = Typeface.createFromAsset(ctx.getAssets(), fontName); typefaces.put(fontName, typeface); } return typeface; } }
通过这种方式,应用程序只能访问每项资产一次的资产,并将其保存在内存中以备不时之需。
不幸的是,Android不提供你想要改变整个应用的字体的快速,简单和干净的方式。 但最近我已经研究了这个问题,并创build了一些工具,允许您在没有任何编码的情况下更改字体(您可以通过xml,样式甚至文本外观来完成)。 他们基于类似的解决scheme,就像你在这里的其他答案中看到的,但考虑到更多的灵活性。 你可以阅读这个博客的所有信息,并在这里看到github项目。
这是一个如何应用这些工具的例子。 把所有的字体文件放在assets/fonts/
。 然后,在xml文件(例如res/xml/fonts.xml
)中声明这些字体,并使用TypefaceManager.initialize(this, R.xml.fonts);
在应用程序的早期加载该文件TypefaceManager.initialize(this, R.xml.fonts);
(例如,在您的应用程序类的onCreate)。 xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?> <familyset> <!-- Some Font. Can be referenced with 'someFont' or 'aspergit' --> <family> <nameset> <name>aspergit</name> <name>someFont</name> </nameset> <fileset> <file>Aspergit.ttf</file> <file>Aspergit Bold.ttf</file> <file>Aspergit Italic.ttf</file> <file>Aspergit Bold Italic.ttf</file> </fileset> </family> <!-- Another Font. Can be referenced with 'anotherFont' or 'bodoni' --> <family> <nameset> <name>bodoni</name> <name>anotherFont</name> </nameset> <fileset> <file>BodoniFLF-Roman.ttf</file> <file>BodoniFLF-Bold.ttf</file> </fileset> </family> </familyset>
现在,您可以在您的样式或xml中使用这些字体(只要您使用上述工具),在您的xml布局中使用自定义UI元素com.innovattic.font.FontTextView
。 在下面,您可以看到如何通过编辑res/values/styles.xml
来将字体应用于整个应用中的所有文本:
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <!-- Application theme --> <!-- Use a different parent if you don't want Holo Light --> <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <item name="android:textViewStyle">@style/MyTextViewStyle</item> </style> <!-- Style to use for ALL text views (including FontTextView) --> <!-- Use a different parent if you don't want Holo Light --> <style name="MyTextViewStyle" parent="@android:style/Widget.Holo.Light.TextView"> <item name="android:textAppearance">@style/MyTextAppearance</item> </style> <!-- Text appearance to use for ALL text views (including FontTextView) --> <!-- Use a different parent if you don't want Holo Light --> <style name="MyTextAppearance" parent="@android:style/TextAppearance.Holo"> <!-- Alternatively, reference this font with the name "aspergit" --> <!-- Note that only our own TextView's will use the font attribute --> <item name="flFont">someFont</item> <item name="android:textStyle">bold|italic</item> </style> <!-- Alternative style, maybe for some other widget --> <style name="StylishFont"> <item name="flFont">anotherFont</item> <item name="android:textStyle">normal</item> </style> </resources>
随着res/layout/layout.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <!-- This text view is styled with the app theme --> <com.innovattic.font.FontTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This uses my font in bold italic style" /> <!-- This text view is styled here and overrides the app theme --> <com.innovattic.font.FontTextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:flFont="anotherFont" android:textStyle="normal" android:text="This uses another font in normal style" /> <!-- This text view is styled with a style and overrides the app theme --> <com.innovattic.font.FontTextView style="@style/StylishFont" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This also uses another font in normal style" /> </LinearLayout>
不要忘记在Android清单中应用主题。
我不知道它是否改变了整个应用程序,但我已经设法改变了一些不能改变的组件:
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Lucida Sans Unicode.ttf"); Typeface.class.getField("DEFAULT").setAccessible(true); Typeface.class.getField("DEFAULT_BOLD").setAccessible(true); Typeface.class.getField("DEFAULT").set(null, tf); Typeface.class.getField("DEFAULT_BOLD").set(null, tf);
我已经在这个链接上find了一步一步的信息,链接: https : //github.com/jaydipumaretiya/CustomTypeface/
在android中有很多方法可以正确使用字体,你必须把你的字体文件直接放在主目录下的资源文件夹中,并且可以使用它运行时。
其他最简单的方法是使用默认库在你的xml文件中设置字体。 我更喜欢这个自定义字体库设置字体为TextView,EditText,Button,CheckBox,RadioButton和AutoCompleteTextView和其他wedget在android中。
Android 8.0(API级别26)引入了XML中的新function字体。您可以创buildfontFamily文件并将其设置为styles.xml。
要将字体添加为资源,请在Android Studio中执行以下步骤:
1.右键单击res文件夹并转到新build> Android资源目录。 出现“新build资源目录”窗口。
2.在资源types列表中select字体,然后单击确定。 注意:资源目录的名称必须是字体。
3.将您的字体文件添加到字体文件夹中。
要创build字体系列,请执行以下步骤:
1.右键单击字体文件夹并转到新build>字体资源文件。 出现“新build资源文件”窗口。
2.input文件名,然后单击确定。 新的字体资源XML在编辑器中打开。
3.在元素中包含每个字体文件,样式和重量属性。 以下XML说明了在字体资源XML中添加与字体相关的属性:
<?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>
将字体添加到样式
打开styles.xml,并将fontFamily属性设置为您要访问的字体文件。
<style name="customfontstyle" parent="@android:style/TextAppearance.Small"> <item name="android:fontFamily">@font/lobster</item> </style>
来源: XML中的字体