Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 706
koti Avatar asked Apr 04 '14 12:04

koti


2 Answers

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);
like image 184
Krunal Indrodiya Avatar answered Oct 13 '22 01:10

Krunal Indrodiya


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);
like image 45
kaushik parmar Avatar answered Oct 13 '22 01:10

kaushik parmar