我似乎无法在我的应用程序中将标准 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
可下载字体。
我们可以为自定义 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 布局上使用它
<com.packagename.RobotoTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"/>
这是一个伟大而简短的方法:
1-创建一个文件夹中命名font
的res
文件夹。2-然后将您的字体文件放入font
您创建的文件夹中。(我们假设您的字体文件名是sample_font.ttf
) 3- 现在在名为的字体文件夹中
创建一个xmlsample.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
现在运行你的应用程序,你会看到你的应用程序字体发生了变化。
你可以试试这个,从我的工作代码(在 Kotlin 中)
如果您在其他一些类文件中,请使用这个
var typeFaceBold: Typeface? =
this.getApplicationContext()?.let { ResourcesCompat.getFont(it, R.font.sans_serif_bold) }
tvAnonymousText.typeface = typeFaceBold
如果你在Activity中使用它,那么你可以这样写
var typeFaceBold: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.sans_serif_bold) }
tvAnonymousText.typeface = typeFaceBold