[英]How to set custom font for word in a TextView text
我想为一个单词设置自定义字体,该单词出现在字符串中的任何位置。
例:海@abc你好吗? 亲爱的朋友你好,你在哪里@abc
在上面的例子中,我必须为“abc”应用自定义字体。 我尝试过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);
但它影响整个字符串。 请指导我如何实现它。
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
在TextView中显示
textview.setText(sb);
请参阅: https : //stackoverflow.com/a/10828482/2480911
如果您想应用自定义文本
//在这里给出字体路径 在我的情况下,我把字体放在资产文件夹中。
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);
您可以使用html管理它或在textview中设置自定义字体样式。
1)如果这种情况在极少数情况下,那么使用这样的set html文本,
TextView txtComments = (TextView)view.findViewById(R.id.tv_comments);
txtComments.setText(Html.fromHtml("Hi<font color=""#FF0000"">abc</font>"));
否则设置这样的自定义字体。
2)
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/Kokila.ttf");
txtyour.setTypeface(type);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.