如何更改字体样式或覆盖默认字体样式以在Xamarin.Android中完成应用程序 [英] How to change font style or override default font style for complete Application in Xamarin.Android
问题描述
我发现有很多帖子说使用 FontAttribute =""Font_Syle.tff#Font_Style"
从xaml文件中静态更改每个 label/entry/button/etc等
的字体样式>或通过为每个属性(例如 label/entry/button/etc
&分别为每个人更改 TypeFace
.
I found many post saying to change font style of every label/entry/button/etc etc
statically from xaml files using FontAttribute="Font_Syle.tff#Font_Style"
or by making the custom renderer for every of property like label/entry/button/etc
& change TypeFace
for everyone of it individually.
[assembly: ExportRenderer(typeof(Label), typeof(CustomLabel))]
namespace *******.Droid.Renderers
{
public class CustomLabel : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var label = (TextView)Control;
Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Montserrat_Regular.ttf");
label.Typeface = font;
}
}
}
但是在将字体设置为对话框,进度对话框,标题,以编程方式静态创建的列表等方面存在问题.
But there was a problem in setting the font to dialog boxes, progress dialogs, titles, statically created List by programmatically, etc.
推荐答案
最后找到了解决方案,可以更改整个应用程序的字体.
Finally found a solution to do so, which can change the font of the complete application.
(有很多针对Java的解决方案,但C#中没有解决方案,因此请在此处发布,这可能会对将来的人有所帮助)
(There are many solutions for Java but none in C# soo posting it here, it might be helpful for someone in future)
代码段
- 将其添加到Resource/values/style.xml中.请记住将其放置在您的应用主题的主父
STYLE
中.
<item name="android:typeface">serif</item>
- 在Droid项目中创建新文件名
TypefaceUtil
using Android.Content;
using Android.Graphics;
using Java.Lang;
namespace ***********.Droid
{
public class TypefaceUtil
{
/**
* Using reflection to override default typeface
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
* @param context to work with assets
* @param defaultFontNameToOverride for example "monospace"
* @param customFontFileNameInAssets file name of the font from assets
*/
public static void overrideFont(Context context, string defaultFontNameToOverride, string customFontFileNameInAssets)
{
try
{
var typeFace = Class.FromType(typeof(Typeface));
var customfont = Typeface.CreateFromAsset(context.Assets, customFontFileNameInAssets);
var font = typeFace.GetDeclaredField(defaultFontNameToOverride);
font.Accessible = true;
font.Set(null, customfont);
}
catch (System.Exception e)
{
var error = e.Message;
}
}
}
}
- 在扩展Application的MainActivity中,调用上面创建的方法.
public class MainApplication : Application
{
public override void OnCreate()
{
base.OnCreate();
TypefaceUtil.overrideFont(Context, "SERIF", "Montserrat_Regular.ttf"); // font from assets: "assets/fonts/Montserrat_Regular.ttf
}
}
注意:将您的Font tff文件放置在Resource的Asset文件夹中
Note: Place your Font tff file in Asset folder of Resource
仅此而已,所有字体都已设置&准备出发了:)
That's all, font is all set & ready to go :)
这篇关于如何更改字体样式或覆盖默认字体样式以在Xamarin.Android中完成应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!