我正在尝试为我的应用应用自定义字体样式。我知道:
Typeface tf = Typeface.createFromAsset(getAssets(),"font.ttf");
text.setTypeface(tf);
但我想为整个应用程序应用自定义字体样式,包括操作栏选项卡和所有文本视图。
有没有一种“超级”的方式来为整个应用程序应用自定义字体?
我正在尝试为我的应用应用自定义字体样式。我知道:
Typeface tf = Typeface.createFromAsset(getAssets(),"font.ttf");
text.setTypeface(tf);
但我想为整个应用程序应用自定义字体样式,包括操作栏选项卡和所有文本视图。
有没有一种“超级”的方式来为整个应用程序应用自定义字体?
无法设置整个应用程序的字体,但如果您正在寻找更通用的编程解决方案,我创建了一个静态类,可用于设置整个视图(活动 UI)的字体。请注意,我正在使用 Mono (C#),但您可以使用 Java 轻松实现它。
您可以将要自定义的布局或特定视图传递给此类。如果你想变得超级高效,你可以使用单例模式来实现它。
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");
}
}
}
在您的活动中,您将需要创建一个字体对象。我使用放置在我的 Resources/Assets/ 目录中的 .ttf 文件在 OnCreate() 中创建我的。确保该文件在其属性中标记为 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);
}