Sam*_*muh 266 java android android-fonts
我需要为我的整个应用程序使用某些字体.我有相同的.ttf文件.是否可以在应用程序启动时将其设置为默认字体,然后在应用程序的其他位置使用它?设置后,如何在布局XML中使用它?
wes*_*ton 448
是的反思.这是有效的(根据这个答案):
(注意:由于缺乏对自定义字体的支持,这是一种解决方法,所以如果你想改变这种情况,请在这里做明星向上投票安卓问题).注意:不要在这个问题上留下"我也是"的评论,每个看过它的人都会收到一封电子邮件.所以请"明星"吧.
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要重载几个默认字体,例如在应用程序类中:
public final class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
}
}
Run Code Online (Sandbox Code Playgroud)
或者当然如果你使用相同的字体文件,你可以改进它只加载一次.
但是我倾向于覆盖一个,比如说"MONOSPACE",然后设置一个样式来强制该字体字体应用程序:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
Run Code Online (Sandbox Code Playgroud)
我已经在评论中调查了它不起作用的报告,它似乎与主题不兼容android:Theme.Material.Light.
如果该主题对您不重要,请使用较旧的主题,例如:
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>
Run Code Online (Sandbox Code Playgroud)
小智 64
在android中有一个很棒的自定义字体库:书法
这是一个如何使用它的示例.
在Gradle中,您需要将此行放入应用程序的build.gradle文件中:
dependencies {
compile 'uk.co.chrisjenx:calligraphy:2.2.0'
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个扩展Application和编写此代码的类:
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("your font path")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
}
Run Code Online (Sandbox Code Playgroud)
并且在activity类中将此方法放在onCreate之前:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
Run Code Online (Sandbox Code Playgroud)
你的清单文件应该是这样的最后一件事:
<application
.
.
.
android:name=".App">
Run Code Online (Sandbox Code Playgroud)
它会将整个活动改为你的字体!它简单而干净!
Tom*_*Tom 47
虽然这不适用于整个应用程序,但它适用于活动,可以重复用于任何其他活动.我已经更新了我的代码,感谢@ FR073N以支持其他视图.我不知道有问题Buttons,RadioGroups等等,因为这些都可以扩展类TextView所以他们应该只是罚款.我为使用反射添加了一个布尔条件,因为它似乎非常hackish并且可能会显着地影响性能.
注意:正如所指出的,这不适用于动态内容!为此,可以用一个onCreateView或一个getView方法来调用这个方法,但需要额外的努力.
/**
* Recursively sets a {@link Typeface} to all
* {@link TextView}s in a {@link ViewGroup}.
*/
public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect)
{
if (mContainer == null || mFont == null) return;
final int mCount = mContainer.getChildCount();
// Loop through all of the children.
for (int i = 0; i < mCount; ++i)
{
final View mChild = mContainer.getChildAt(i);
if (mChild instanceof TextView)
{
// Set the font if it is a TextView.
((TextView) mChild).setTypeface(mFont);
}
else if (mChild instanceof ViewGroup)
{
// Recursively attempt another ViewGroup.
setAppFont((ViewGroup) mChild, mFont);
}
else if (reflect)
{
try {
Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
mSetTypeface.invoke(mChild, mFont);
} catch (Exception e) { /* Do something... */ }
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用它你会做这样的事情:
final Typeface mFont = Typeface.createFromAsset(getAssets(),
"fonts/MyFont.ttf");
final ViewGroup mContainer = (ViewGroup) findViewById(
android.R.id.content).getRootView();
HomeActivity.setAppFont(mContainer, mFont);
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
Phi*_*o99 34
综上所述:
选项#1: 使用反射来应用字体(结合weston和Roger Huang的答案):
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,final Typeface newTypeface) {
if (isVersionGreaterOrEqualToLollipop()) {
Map<String, Typeface> newMap = new HashMap<String, Typeface>();
newMap.put("sans-serif", newTypeface);
try {
final Field staticField = Typeface.class.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Application类中的用法:
public final class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
}
}
Run Code Online (Sandbox Code Playgroud)
设置一个样式来强制该字体字体应用程序(基于lovefish):
预棒棒糖:
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
Run Code Online (Sandbox Code Playgroud)
棒棒糖(API 21):
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:textAppearance">@style/CustomTextAppearance</item>
</style>
<style name="CustomTextAppearance">
<item name="android:typeface">monospace</item>
</style>
</resources>
Run Code Online (Sandbox Code Playgroud)
选项2:将 每个视图子类化为您需要自定义字体的位置,即.ListView,EditTextView,Button等(Palani的回答):
public class CustomFontView extends TextView {
public CustomFontView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomFontView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomFontView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
setTypeface(tf);
}
}
Run Code Online (Sandbox Code Playgroud)
选项3: 实现遍历当前屏幕视图层次结构的View Crawler:
变化#1(汤姆的回答):
public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect)
{
if (mContainer == null || mFont == null) return;
final int mCount = mContainer.getChildCount();
// Loop through all of the children.
for (int i = 0; i < mCount; ++i)
{
final View mChild = mContainer.getChildAt(i);
if (mChild instanceof TextView)
{
// Set the font if it is a TextView.
((TextView) mChild).setTypeface(mFont);
}
else if (mChild instanceof ViewGroup)
{
// Recursively attempt another ViewGroup.
setAppFont((ViewGroup) mChild, mFont);
}
else if (reflect)
{
try {
Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
mSetTypeface.invoke(mChild, mFont);
} catch (Exception e) { /* Do something... */ }
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
final ViewGroup mContainer = (ViewGroup) findViewById(
android.R.id.content).getRootView();
HomeActivity.setAppFont(mContainer, Typeface.createFromAsset(getAssets(),
"fonts/MyFont.ttf"));
Run Code Online (Sandbox Code Playgroud)
变体#2:https: //coderwall.com/p/qxxmaa/android-use-a-custom-font-everywhere.
选项#4: 使用名为Calligraphy的第三方Lib .
就个人而言,我会推荐选项#4,因为它可以节省很多麻烦.
Rog*_*ang 28
我想改进weston对API 21 Android 5.0的回答.
在API 21下,大多数文本样式都包含fontFamily设置,如:
<style name="TextAppearance.Material">
<item name="fontFamily">@string/font_family_body_1_material</item>
</style>
Run Code Online (Sandbox Code Playgroud)
哪个适用默认的Roboto Regular字体:
<string name="font_family_body_1_material">sans-serif</string>
Run Code Online (Sandbox Code Playgroud)
原始答案无法应用等宽字体,因为android:fontFamily对android:typeface属性(引用)具有更高的优先级.使用Theme.Holo.*是一个有效的解决方法,因为里面没有android:fontFamily设置.
由于Android 5.0将系统字体放在静态变量Typeface.sSystemFontMap(引用)中,我们可以使用相同的反射技术来替换它:
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
if (isVersionGreaterOrEqualToLollipop()) {
Map<String, Typeface> newMap = new HashMap<String, Typeface>();
newMap.put("sans-serif", newTypeface);
try {
final Field staticField = Typeface.class
.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Pal*_*ani 15
它非常简单...... 1.下载并将自定义字体放入资产中..然后为文本视图编写一个单独的类,如下所示:这里我使用了futura字体
public class CusFntTextView extends TextView {
public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CusFntTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CusFntTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
setTypeface(tf);
}
}
Run Code Online (Sandbox Code Playgroud)
}
并在xml中执行以下操作:
<com.packagename.CusFntTextView
android:id="@+id/tvtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi Android"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
Run Code Online (Sandbox Code Playgroud)
我还建议扩展TextView和其他控件,但我认为在构造中设置字体会更好.
public FontTextView(Context context) {
super(context);
init();
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
protected void init() {
setTypeface(Typeface.createFromAsset(getContext().getAssets(), AppConst.FONT));
}
Run Code Online (Sandbox Code Playgroud)
我希望通过主题为" Theme.AppCompat "的API 21 Android棒棒糖来改进weston和Roger Huang的答案.
Android 4.4以下
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
Run Code Online (Sandbox Code Playgroud)
超过(相等)API 5.0
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:textAppearance">@style/CustomTextAppearance</item>
</style>
<style name="CustomTextAppearance">
<item name="android:typeface">monospace</item>
</style>
</resources>
Run Code Online (Sandbox Code Playgroud)
而FontsOverride util的文件是一样的东西在韦斯顿的答案.我在这些手机上测试过:
Nexus 5(android 5.1主Android系统)
中兴V5(android 5.1 CM12.1)
XIAOMI note(android 4.4 MIUI6)
HUAWEI C8850(android 2.3.5 UNKNOWN)
可以在这里找到一个出色的解决方案:https://coderwall.com/p/qxxmaa/android-use-a-custom-font-everywhere.
只需从BaseActivity扩展活动并编写这些方法.此外,您应该更好地缓存字体,如下所述:https://stackoverflow.com/a/16902532/2914140.
经过一些研究,我编写了适用于三星Galaxy Tab A(Android 5.0)的代码.使用的代码为weston和Roger Huang以及/sf/answers/2326527171/.也在联想TAB 2 A10-70L上进行了测试,但它不起作用.我在这里插入了一个字体'Comic Sans'以便看到差异.
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.util.Log;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class FontsOverride {
private static final int BOLD = 1;
private static final int BOLD_ITALIC = 2;
private static final int ITALIC = 3;
private static final int LIGHT = 4;
private static final int CONDENSED = 5;
private static final int THIN = 6;
private static final int MEDIUM = 7;
private static final int REGULAR = 8;
private Context context;
public FontsOverride(Context context) {
this.context = context;
}
public void loadFonts() {
Map<String, Typeface> fontsMap = new HashMap<>();
fontsMap.put("sans-serif", getTypeface("comic.ttf", REGULAR));
fontsMap.put("sans-serif-bold", getTypeface("comic.ttf", BOLD));
fontsMap.put("sans-serif-italic", getTypeface("comic.ttf", ITALIC));
fontsMap.put("sans-serif-light", getTypeface("comic.ttf", LIGHT));
fontsMap.put("sans-serif-condensed", getTypeface("comic.ttf", CONDENSED));
fontsMap.put("sans-serif-thin", getTypeface("comic.ttf", THIN));
fontsMap.put("sans-serif-medium", getTypeface("comic.ttf", MEDIUM));
overrideFonts(fontsMap);
}
private void overrideFonts(Map<String, Typeface> typefaces) {
if (Build.VERSION.SDK_INT == 21) {
try {
final Field field = Typeface.class.getDeclaredField("sSystemFontMap");
field.setAccessible(true);
Map<String, Typeface> oldFonts = (Map<String, Typeface>) field.get(null);
if (oldFonts != null) {
oldFonts.putAll(typefaces);
} else {
oldFonts = typefaces;
}
field.set(null, oldFonts);
field.setAccessible(false);
} catch (Exception e) {
Log.e("TypefaceUtil", "Cannot set custom fonts");
}
} else {
try {
for (Map.Entry<String, Typeface> entry : typefaces.entrySet()) {
final Field staticField = Typeface.class.getDeclaredField(entry.getKey());
staticField.setAccessible(true);
staticField.set(null, entry.getValue());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private Typeface getTypeface(String fontFileName, int fontType) {
final Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/" + fontFileName);
return Typeface.create(tf, fontType);
}
}
Run Code Online (Sandbox Code Playgroud)
要在整个应用程序中运行代码,您应该在类似Application的类中编写以下内容:
new FontsOverride(this).loadFonts();
Run Code Online (Sandbox Code Playgroud)
在'assets'中创建一个'fonts'文件夹,并在那里放置所需的字体.可以在此处找到一条简单的说明:https://stackoverflow.com/a/31697103/2914140.
Lenovo设备也错误地获取字体值.在大多数情况下,它返回Typeface.NORMAL,有时为null.即使TextView是粗体(在xml文件布局中).请参见此处:TextView isBold始终返回NORMAL.这样,屏幕上的文本始终采用自然字体,而不是粗体或斜体.所以我认为这是制片人的错误.
为Xamarin.Android工作:
类:
public class FontsOverride
{
public static void SetDefaultFont(Context context, string staticTypefaceFieldName, string fontAssetName)
{
Typeface regular = Typeface.CreateFromAsset(context.Assets, fontAssetName);
ReplaceFont(staticTypefaceFieldName, regular);
}
protected static void ReplaceFont(string staticTypefaceFieldName, Typeface newTypeface)
{
try
{
Field staticField = ((Java.Lang.Object)(newTypeface)).Class.GetDeclaredField(staticTypefaceFieldName);
staticField.Accessible = true;
staticField.Set(null, newTypeface);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
应用实施:
namespace SomeAndroidApplication
{
[Application]
public class App : Application
{
public App()
{
}
public App(IntPtr handle, JniHandleOwnership transfer)
: base(handle, transfer)
{
}
public override void OnCreate()
{
base.OnCreate();
FontsOverride.SetDefaultFont(this, "MONOSPACE", "fonts/Roboto-Light.ttf");
}
}
}
Run Code Online (Sandbox Code Playgroud)
样式:
<style name="Theme.Storehouse" parent="Theme.Sherlock">
<item name="android:typeface">monospace</item>
</style>
Run Code Online (Sandbox Code Playgroud)
从Android O开始,现在可以直接从XML定义,我的bug现已关闭!
TL; DR:
首先,您必须将字体添加到项目中
其次你添加一个字体系列,如下所示:
<?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>
Run Code Online (Sandbox Code Playgroud)
最后,您可以在布局或样式中使用该字体:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>
Run Code Online (Sandbox Code Playgroud)
请享用!
Sel*_*mar -15
是的,可以为整个应用程序设置字体。
实现此目的的最简单方法是将所需的字体与您的应用程序打包在一起。
为此,只需在项目根目录中创建一个asset/ 文件夹,然后将字体(TrueType 或 TTF 形式)放入 asset 中。
例如,您可以创建asset/fonts/ 并将 TTF 文件放入其中。
public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148972 次 |
| 最近记录: |