如何设置android应用程序的自定义字体?

我似乎无法将标准的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

我们可以为自定义的textView创建类。 例如,我们需要使用roboto字体的textview

 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) } } } 

那么我们可以在每个xml布局中使用它

  

试试这个, 从SEGUN的这个教程 :

 val myCustomFont : Typeface? = ResourcesCompat.getFont(this, R.font.my_font) myView.typeface = myCustomFont 

注意:您需要在项目中下载.ttf字体,而不仅仅是可下载字体的.xml