简体   繁体   中英

How to set custom font for word in a TextView text

I want to set custom font for a word which is appears any where in a string.

Ex : Hai @abc how are you ? , Hello my dear friend where you @abc

In the above examples, i have to apply custom font for "abc". I tried with Spannable class, but i am unable to get it.

final TextView txtComments = (TextView)view.findViewById(R.id.tv_comments);  
SpannableStringBuilder SS = new SpannableStringBuilder(alcomments.get(i));
SS.setSpan (new CustomTypefaceSpan("", tf), 0, SS.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
txtComments.setText(SS);

But it is affecting the entire string. Please guide me how to achieve it.

First Part Not Bold   BOLD  rest not bold

String normalBefore= "First Part Not Bold ";
String normalBOLD=  "BOLD ";
String normalAfter= "rest not bold";
String finalString= normalBefore+normalBOLD+normalAfter;
Spannable sb = new SpannableString( finalString );
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), finalString.indexOf(normalBOLD), normalBOLD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //bold
sb.setSpan(new AbsoluteSizeSpan(intSize), finalString.indexOf(normalBOLD), normalBOLD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//resize size

to show this in TextView

textview.setText(sb);

Refer : https://stackoverflow.com/a/10828482/2480911

If you want to apply custom text then

//Give Font path here. In my case i put font in asset folder.

String fontPath = "bankgthd.ttf";

    // text view label


final TextView txtComments = (TextView)view.findViewById(R.id.tv_comments);  

    // Loading Font Face


Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);

    // Applying font


txtGhost.setTypeface(tf);

you can manage this using html or set custom font style in textview.

1) if this scenario is in rare case then go with set html text like this,

TextView txtComments = (TextView)view.findViewById(R.id.tv_comments); 
txtComments.setText(Html.fromHtml("Hi<font color=""#FF0000"">abc</font>"));

else set custom font like this.

2)

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/Kokila.ttf"); 
txtyour.setTypeface(type);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM