我似乎无法在我的应用程序中将标准的android字体更改为另一个。我在Kotlin写了我的应用程序,而且我正在使用Anko来解决它。我试过了:
typeface = Typeface.create()
typeface = Typface.createFromAsset(assets, "font/font_name")
setTypeface(Typeface.createFromAsset(assets, "font/font_name"))
感谢您的帮助。
答案 0 :(得分:4)
我在使用Kotlin的Android Studio 3.1 Canary上遇到了同样的问题
以下是解决方案: font / lobster_regular.ttf file
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
答案 1 :(得分:2)
val myCustomFont : Typeface? = ResourcesCompat.getFont(this, R.font.my_font)
myView.typeface = myCustomFont
注意:您需要在项目中下载.ttf
字体才能执行此操作 - 而不仅仅是.xml
可下载字体。
答案 2 :(得分:1)
我们可以为自定义textView创建类。例如,我们需要带有roboto字体的textview
<com.packagename.RobotoTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"/>
然后我们可以在每个xml布局上使用它
{{1}}
答案 3 :(得分:1)
这是一种简便的方法:
1-在 font
文件夹中创建一个名为 res
的文件夹。
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
现在运行您的应用程序,您将看到应用程序字体已更改。
答案 4 :(得分:0)
您可以从我的工作代码(在Kotlin中)中尝试这一点
如果您在其他Class文件中,请使用此文件
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