我似乎无法在我的应用程序中更改标准的Android字体为其他字体。 我使用Kotlin编写我的应用程序,使用Anko进行布局。 我已尝试过:
typeface = Typeface.create()
typeface = Typface.createFromAsset(assets, "font/font_name")
setTypeface(Typeface.createFromAsset(assets, "font/font_name"))
感谢您的帮助。
我似乎无法在我的应用程序中更改标准的Android字体为其他字体。 我使用Kotlin编写我的应用程序,使用Anko进行布局。 我已尝试过:
typeface = Typeface.create()
typeface = Typface.createFromAsset(assets, "font/font_name")
setTypeface(Typeface.createFromAsset(assets, "font/font_name"))
我在使用带Kotlin的Android Studio 3.1 Canary时遇到了同样的问题。
这是解决方案:针对font/lobster_regular.ttf文件
var typeFace: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.lobster_regular)
示例:
private var _customFontTextView: TextView? = null
private var _typeFace: Typeface? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_main)
this._initializeResources()
this._initializeGUI()
}
private fun _initializeResources() {
this._customFontTextView = this.findViewById(R.id.custom_font_text_view)
this._typeFace = ResourcesCompat.getFont(this.applicationContext, R.font.lobster_regular)
}
private fun _initializeGUI() {
this._customFontTextView!!.setTypeface(this._typeFace, Typeface.NORMAL)
}
你还可以通过可下载字体实现更多功能,这是来自 Google 的文章: https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts.html
请参考SEGUN的这篇教程,尝试以下方法:
val myCustomFont : Typeface? = ResourcesCompat.getFont(this, R.font.my_font)
myView.typeface = myCustomFont
注意:如果您要这样做,您需要在项目中下载 .ttf
字体,而不仅仅是可下载字体的 .xml
文件。
这是一个简单而好用的方法:
1- 在res
文件夹中创建名为font
的文件夹。
2- 将字体文件放入您创建的font
文件夹中。(我们假设您的字体文件名为sample_font.ttf
)
3- 现在在字体文件夹中创建一个名为sample.xml
的xml文件,并将以下代码放入其中。
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:font="@font/sample_font"
android:fontStyle="normal"
android:fontWeight="500" />
</font-family>
4- 现在打开 res/values/styles.xml
文件,然后在主题样式(通常命名为 AppTheme
)中添加以下代码行:
<item name="fontFamily">@font/sample</item> //put name of xml file in the font folder
class RobotoTextView(context: Context?, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {
init {
val typeface = Typeface.createFromAsset(getContext().assets, "font/roboto.ttf")
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB ||
android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
setTypeface(typeface)
}
}
}
<com.packagename.RobotoTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"/>
你可以尝试这个,来自我的工作代码(使用 Kotlin)
如果你在其他类文件中,则使用这个
var typeFaceBold: Typeface? =
this.getApplicationContext()?.let { ResourcesCompat.getFont(it, R.font.sans_serif_bold) }
tvAnonymousText.typeface = typeFaceBold
var typeFaceBold: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.sans_serif_bold) }
tvAnonymousText.typeface = typeFaceBold