同一个TextView中string的不同字体大小

我有一个textView里面有一个数字(variables)和一个string ,我怎么能给一个比string大一号? 代码:

 TextView size = (TextView)convertView.findViewById(R.id.privarea_list_size); if (ls.numProducts != null) { size.setText(ls.numProducts + " " + mContext.getString(R.string.products)); } 

我想ls.numproducts有一个不同于其他文本的大小。 怎么做?

使用可Spannablestring

  String s= "Hello Everyone"; SpannableString ss1= new SpannableString(s); ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color TextView tv= (TextView) findViewById(R.id.textview); tv.setText(ss1); 

快照

在这里输入图像描述

您可以使用空格拆分string,并将span添加到所需的string中。

  String s= "Hello Everyone"; String[] each = s.split(" "); 

现在将span应用于string并将其添加到textview。

万一你想知道如何在同一个textview中设置多个不同的大小,但是使用绝对大小而不是相对大小,你可以使用AbsoluteSpan来代替RelativeSpan

只需获取所需文字大小的像素尺寸

 int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1); int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2); 

然后基于文本创build一个新的AbsoluteSpan

 String text1 = "Hi"; String text2 = "there"; SpannableString span1 = new SpannableString(text1); span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE); SpannableString span2 = new SpannableString(text2); span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE); // let's put both spans together with a separator and all CharSequence finalText = TextUtils.concat(span1, " ", span2); 

您可以使用htmlstring完成此操作,并使用HTML设置Textview
txtView.setText(Html.fromHtml("Your html string here"));

例如 :

 txtView.setText(Html.fromHtml("<html><body><font size=5 color=red>Hello </font> World </body><html>"));` 

试试spannableStringbuilder 。 使用这个我们可以创build多个字体大小的string。