在Android中将自定义字体添加到主题中
在Android中将自定义字体添加到主题中
在Android的主题中有没有办法添加自定义字体?
我已经阅读了快速提示:自定义Android字体,但是在这里我们必须通过编程方式将自定义字体添加到文本中。
TextView txt = (TextView) findViewById(R.id.custom_font); Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf"); txt.setTypeface(font);
但是我想通过样式/主题来设置自定义字体。
将自定义字体添加到Android主题中的原因是因为Android不提供一种快速、简单和清晰的方式来更改应用程序的整个字体。然而,最近我研究了这个问题,并创建了一些工具,允许您在不进行任何编码的情况下更改字体(您可以通过xml、样式甚至文本外观来完成所有操作)。这些工具基于类似的解决方案,可以提供更大的灵活性。您可以在这个博客上阅读有关它们的所有信息,并在这里查看GitHub项目。
以下是如何应用这些工具的示例。将所有字体文件放在assets/fonts/
中。然后,在您的应用程序中的早期声明这些字体,使用TypefaceManager.initialize(this, R.xml.fonts);
(例如,在您的Application类的onCreate中)。xml文件如下所示:
aspergit someFont Aspergit.ttf Aspergit Bold.ttf Aspergit Italic.ttf Aspergit Bold Italic.ttf bodoni anotherFont BodoniFLF-Roman.ttf BodoniFLF-Bold.ttf
现在,您可以在样式或xml中使用这些字体(前提是您使用了上述提到的工具),通过在自定义TextView com.innovattic.font.FontTextView
的xml布局中设置flFont属性。下面是您如何通过编辑res/values/styles.xml
将字体应用于应用程序中的所有文本的示例:
附带的res/layout/layout.xml
文件如下:
不要忘记在Android清单文件中应用主题。
由于您还使用了Java代码,因此我们可以以更简单的方式完成。但是,这实际上应该是Android的本机功能。
问题的出现原因:开发者想要在Android应用中添加自定义字体,但不清楚如何实现。
解决方法:开发者可以使用FontUtils类来帮助实现添加自定义字体的功能。首先,在运行时的活动中,开发者可以使用以下代码来设置自定义字体:
FontUtils.setCustomFont(findViewById(R.id.top_view), getAssets());
此外,开发者也可以在XML中使用以下代码来设置自定义字体:
<TextView android:id="@+id/my_label" android:tag="condensed" android:text="/label" ... />
理论上,开发者可以创建一个样式并与FontUtils的运行时代码一起使用:
<style name="roboto_condensed"> <item name="android:tag">condensed,your-own-css-like-language-here</item> </style>
FontUtils类中的代码会根据TextView的标签设置自定义字体。如果标签包含"bold",则设置为粗体字体;如果包含"condensed",则设置为紧凑字体;如果包含"light",则设置为轻字体;否则,设置为普通字体。
最后,开发者可以使用以下代码来设置自定义字体:
public static void setCustomFont(View topView, AssetManager assetsManager) { if (normal == null || bold == null || condensed == null || light == null) { normal = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Regular.ttf"); bold = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Bold.ttf"); condensed = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Condensed.ttf"); light = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Light.ttf"); } if (topView instanceof ViewGroup) { setCustomFont((ViewGroup) topView); } else if (topView instanceof TextView) { setCustomFont((TextView) topView); } }
这段代码会根据传入的顶层视图和AssetManager来设置自定义字体。如果顶层视图是ViewGroup类型,则会递归处理其子视图;如果是TextView类型,则直接设置自定义字体。
问题的原因是在Android中添加自定义字体到主题时,需要将字体文件放置在assets文件夹中,并在XML布局文件中直接指定字体文件名。解决方法可以参考以下链接:https://stackoverflow.com/questions/8954484/18043863#18043863