I want to make certain part of my text to bold whose value is set using DataBinding with ViewModel.
For e.g
If you are selected, you will pay $160 for your pair.
I am using strings resources
<string name="product_price">If you are selected, you will have to pay $%d for your pair.</string>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/spacing_xlarge"
android:layout_marginStart="@dimen/spacing_xlarge"
android:layout_marginBottom="@dimen/spacing_small"
android:text="@{@string/product_price(productPrice)}"
android:textColor="@color/button_tertiary"
android:visibility="@{productPrice > 0}"
style="@style/Body.Small"
/>
Currently passing product price using ViewModel with Binding by setting binding.setProductPrice(Object.getPrice())
I know the following solutions : But want to try using DataBinding
But all of the above solutions are workaround.
Question ::
Want to try DataBinding feature which can be used to style certain part of string. Just like SpannableString
Manipulate String in the Layout file using DataBinding
android:textStyle attribute is the first and one of the best way to make the text in TextView bold. just use “bold”. If you want to use bold and italic. Use pipeline symbol “|” .
16 + names. length() is where to stop bolding. So I said start bolding after "You have chosen " and stop bolding the length of the name positions after where it started. b is the type of span to apply on the StringBuilder (which is bold).
text. style. StyleSpan(Typeface. BOLD), start, end, Spannable.
Just use getText(R. string.
You have to create a BindingAdapter
and SpannableStringBuilder
.
Binding Adapter
object Util {
@BindingAdapter("main","secondText")
@JvmStatic
fun setBoldString(view: AppCompatTextView, maintext: String,sequence: String) {
view.text = Util.getBoldText(maintext, sequence)
}
@JvmStatic
fun getBoldText(text: String, name: String): SpannableStringBuilder {
val str = SpannableStringBuilder(text)
val textPosition = text.indexOf(name)
str.setSpan(android.text.style.StyleSpan(Typeface.BOLD),
textPosition, textPosition + name.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
return str
}
}
XML
<android.support.v7.widget.AppCompatTextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:main="@{`you will pay $160 for your pair`}"
app:secondText="@{`$160`}"
android:textColor="@color/black"
android:textSize="22sp" />
May be it helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With