[英]How to add font style to textview android kotlin
我需要幫助,我陷入了困境。 我的要求是,我需要在工具提示中添加文本。 我實際上是這樣做的。 但是文本包括多行文本,還有一些行具有粗體樣式,而另一些行具有常規樣式和自定義字體樣式。 通過我正在使用的以下代碼,我可以添加粗體、斜體和常規樣式。 但我需要在文本中添加以下自定義字體樣式。 請查看我的以下代碼。
textViewToShow.setOnClickListener { view ->
val tfBold = Typeface.createFromAsset(
context!!.assets,
"fonts/myriad_pro_bold.ttf"
)
val tfRegular = Typeface.createFromAsset(
context!!.assets,
"fonts/myriad_pro_regular.ttf"
)
var string1 = “Item show in Bold style”
var string2 = “Item show in Regular style”
var string3 = “Item show in Regular style with item description”
val holesTextView = Html.fromHtml("<b>" + string1 + "</b> <br><br> <b><i>"+ string2 + "</i></b> " + string3)
showToolTip(view, holesTextView)
}
private fun showToolTip(view: View, holesTextView: Spanned) {
val builder: Tooltip.Builder =
Tooltip.Builder(view, R.style.Tooltip)
.setText(holesTextView)
builder.show()
}
非常感謝任何解決方案/建議
我會創建一個字體系列
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/myriad_pro_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/myriad_pro_italic" />
<font
android:fontStyle="normal"
android:fontWeight="700"
android:font="@font/myriad_pro_bold" />
</font-family>
遵循如何為粗體字體創建自定義字體系列的答案。
然后您可以在布局中分配字體系列:
<EditText
android:fontFamily="@font/mycustomfont"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, World!" />
或以編程方式:
val typeface = ResourcesCompat.getFont(context, R.font.mycustomfont)
holesTextView.setTypeface(typeface)
或者在工具提示使用其setTypeface()
方法的情況下:
val typeface = ResourcesCompat.getFont(context, R.font.mycustomfont)
val builder: Tooltip.Builder = Tooltip.Builder(view, R.style.Tooltip)
.setText(holesTextView)
.setTypeface(typeface)
builder.show()
並使用HtmlCompat.fromHtml作為Html.fromHtml已棄用:
val holesTextView = HtmlCompat.fromHtml("<b>" + string1 + "</b> <br><br> <b><i>"+ string2 + "</i></b> " + string3, HtmlCompat.FROM_HTML_MODE_LEGACY)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.