简体   繁体   English

如何在TextView文本中为单词设置自定义字体

[英]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 ? 例:海@abc你好吗? , Hello my dear friend where you @abc 亲爱的朋友你好,你在哪里@abc

In the above examples, i have to apply custom font for "abc". 在上面的例子中,我必须为“abc”应用自定义字体。 I tried with Spannable class, but i am unable to get it. 我尝试过Spannable类,但我无法得到它。

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中显示

textview.setText(sb);

Refer : https://stackoverflow.com/a/10828482/2480911 请参阅: 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. 您可以使用html管理它或在textview中设置自定义字体样式。

1) if this scenario is in rare case then go with set html text like this, 1)如果这种情况在极少数情况下,那么使用这样的set html文本,

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) 2)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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