我正在开发一个应用程序,用户可以在其中选择一种字体(他大约有3或4种选择)。该应用程序必须在整个应用程序中具有选定的字体,因此我需要以编程方式进行更改(不涉及XML)。我通过网络服务收到了用户选择的字体。我已经在网上搜索过,但是我阅读的所有解决方案都需要使用XML。
0-该应用程序在资产文件夹中有一些(3-4).ttf文件
1-用户在网络上选择字体。
2- Android应用程序启动,并获取一个表示用户选择的字体的String常量(或int)。
3- Android应用程序根据整个应用程序中的用户选择更改其字体。
有没有办法做到这一点?
要以编程方式更改整个应用程序中的字体,您可以尝试书法库
https://github.com/InflationX/Calligraphy
初始化字体将在Application类中,所以我相信您可以实现所要求的内容
ViewPump.init(ViewPump.builder()
.addInterceptor(new CalligraphyInterceptor(
new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
.setFontAttrId(R.attr.fontPath)
.build()))
.build());
您可以做类似的事情
String fontPath;
if(userSelection == 0) { //userSelection value from the server
fontPath = "fonts/FirstFont.ttf"
} else if (userSelection == 1) {
fontPath = "fonts/SecondFont.ttf"
} else {
fontPath = "fonts/ThirdFont.ttf"
}
ViewPump.init(ViewPump.builder()
.addInterceptor(new CalligraphyInterceptor(
new CalligraphyConfig.Builder()
.setDefaultFontPath(fontPath)
.setFontAttrId(R.attr.fontPath)
.build()))
.build());
我假设您可以从服务器检索用户选择