Reputation: 288
I'm using Xamarin for an Android App and I have a custom TypeFace
created as follows:
Typeface weatherFont = Typeface.CreateFromAsset(Assets, "Weather.ttf");
My problem is that I have a string
that has to be assigned to a TextView
and I need to set the font of the first 3 characters to the default android font and the remaining to my weatherFont
Typeface. How can I do that?
Upvotes: 1
Views: 864
Reputation: 74104
Up to API-27, you need a custom CharacterStyle
subclass to apply a custom Typeface
to a Spannable
.
var sushiFont = Typeface.CreateFromAsset(Assets, "Tastysushi.ttf");
var spannable = new SpannableString("123 = SushiHangover");
spannable.SetSpan (new CustomTypefaceSpan(sushiFont), 3, spannable.Length(), SpanTypes.ExclusiveInclusive);
button.SetText(spannable, TextView.BufferType.Spannable);
Or in API-21(+), you can avoid the SetSpan
char start/end indexing by using SpannableStringBuilder.Append
:
var sushiFont = Typeface.CreateFromAsset(Assets, "Tastysushi.ttf");
var spannableString = new SpannableStringBuilder("123");
var spannable = new SpannableString(" = SushiHangover");
spannableString.Append(spannable, new CustomTypefaceSpan(sushiFont), SpanTypes.ExclusiveInclusive);
button.SetText(spannableString, TextView.BufferType.Spannable);
And in API-28+, you can directly create spans that directly include a different Typeface
without using a CharacterStyle
subclass:
spannableString.Append(spannable, new TypefaceSpan(sushiFont), SpanTypes.ExclusiveInclusive);
public class CustomTypefaceSpan : MetricAffectingSpan
{
readonly Typeface typeFace;
public CustomTypefaceSpan(Typeface typeFace)
{
this.typeFace = typeFace;
}
public override void UpdateDrawState(TextPaint tp)
{
tp.SetTypeface(typeFace);
}
public override void UpdateMeasureState(TextPaint p)
{
p.SetTypeface(typeFace);
}
}
Upvotes: 3