同一 TextView 中字符串的不同字体大小

我有一个 textView里面有一个数字(变量)和一个 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 的大小与文本的其余部分不同。怎么做?

128728 次浏览

您可以使用 html 字符串完成这项工作,并将 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。使用它我们可以创建具有多种字体大小的字符串。

使用 Spannable String

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

快照

enter image description here

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

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

现在将 span应用于 string,并将同样的应用程序添加到 textview

如果您想知道如何在同一个文本视图中设置多个不同的大小,但是使用绝对大小而不是相对大小,那么可以使用 AbsoluteSizeSpan而不是 RelativeSizeSpan来实现这一点。

只需获取所需文本大小的像素维度即可

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

然后根据文本创建一个新的 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);

方法1

public static void increaseFontSizeForPath(Spannable spannable, String path, float increaseTime) {
int startIndexOfPath = spannable.toString().indexOf(path);
spannable.setSpan(new RelativeSizeSpan(increaseTime), startIndexOfPath,
startIndexOfPath + path.length(), 0);
}

使用

Utils.increaseFontSizeForPath(spannable, "big", 3); // make "big" text bigger 3 time than normal text

enter image description here

方法2

public static void setFontSizeForPath(Spannable spannable, String path, int fontSizeInPixel) {
int startIndexOfPath = spannable.toString().indexOf(path);
spannable.setSpan(new AbsoluteSizeSpan(fontSizeInPixel), startIndexOfPath,
startIndexOfPath + path.length(), 0);
}

使用

Utils.setFontSizeForPath(spannable, "big", (int) textView.getTextSize() + 20); // make "big" text bigger 20px than normal text

enter image description here

我已经写了我自己的函数,它接受2个字符串和1个 int (文本大小)

要更改文本大小的全文和文本部分。

它返回一个 SpannableStringBuilder,您可以在文本视图中使用它。

  public static SpannableStringBuilder setSectionOfTextSize(String text, String textToChangeSize, int size){


SpannableStringBuilder builder=new SpannableStringBuilder();


if(textToChangeSize.length() > 0 && !textToChangeSize.trim().equals("")){


//for counting start/end indexes
String testText = text.toLowerCase(Locale.US);
String testTextToBold = textToChangeSize.toLowerCase(Locale.US);
int startingIndex = testText.indexOf(testTextToBold);
int endingIndex = startingIndex + testTextToBold.length();
//for counting start/end indexes


if(startingIndex < 0 || endingIndex <0){
return builder.append(text);
}
else if(startingIndex >= 0 && endingIndex >=0){


builder.append(text);
builder.setSpan(new AbsoluteSizeSpan(size, true), startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}else{
return builder.append(text);
}


return builder;
}
private SpannableStringBuilder SpannableStringBuilder(final String text, final char afterChar, final float reduceBy) {
RelativeSizeSpan smallSizeText = new RelativeSizeSpan(reduceBy);
SpannableStringBuilder ssBuilder = new SpannableStringBuilder(text);
ssBuilder.setSpan(
smallSizeText,
text.indexOf(afterChar),
text.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);


return ssBuilder;
}
------------------------
TextView textView =view.findViewById(R.id.textview);
String s= "123456.24";
textView.setText(SpannableStringBuilder(s, '.', 0.7f));

——————结果——————————

结果:

12345

实现这一点的最佳方法是不使用字符串和完全动态的 Html 例如:

  public static String getTextSize(String text,int size) {
return "<span style=\"size:"+size+"\" >"+text+"</span>";


}

你可以使用颜色属性等。 如果另一方面:

size.setText(Html.fromHtml(getTextSize(ls.numProducts,100) + " " + mContext.getString(R.string.products));

如果您想避免对您的翻译器造成太多的混淆,我想到了一种方法,在字符串中只有一个占位符,这将在代码中处理。

所以,假设你在字符串中有这个:

    <string name="test">
<![CDATA[
We found %1$s items]]>
</string>

如果你想让占位符文本有不同的大小和颜色,你可以这样做:

        val textToPutAsPlaceHolder = "123"
val formattedStr = getString(R.string.test, "$textToPutAsPlaceHolder<bc/>")
val placeHolderTextSize = resources.getDimensionPixelSize(R.dimen.some_text_size)
val placeHolderTextColor = ContextCompat.getColor(this, R.color.design_default_color_primary_dark)
val textToShow = HtmlCompat.fromHtml(formattedStr, HtmlCompat.FROM_HTML_MODE_LEGACY, null, object : Html.TagHandler {
var start = 0
override fun handleTag(opening: Boolean, tag: String, output: Editable, xmlReader: XMLReader) {
when (tag) {
"bc" -> if (!opening) start = output.length - textToPutAsPlaceHolder.length
"html" -> if (!opening) {
output.setSpan(AbsoluteSizeSpan(placeHolderTextSize), start, start + textToPutAsPlaceHolder.length, 0)
output.setSpan(ForegroundColorSpan(placeHolderTextColor), start, start + textToPutAsPlaceHolder.length, 0)
}
}
}
})
textView.text = textToShow

结果就是:

enter image description here

在 kotlin 中按照下面的方法使用 html

HtmlCompat.fromHtml("<html><body><h1>This is Large Heading :-</h1><br>This is normal size<body></html>",HtmlCompat.FROM_HTML_MODE_LEGACY)

科特林爱好者的实用方法

fun String.setFontSizeForPath(path: String, fontSizeInPixel: Int, colorCode: String = "#FF0000"): SpannableString {
val spannable = SpannableString(this)
val startIndexOfPath = spannable.toString().indexOf(path)
spannable.setSpan(
AbsoluteSizeSpan(fontSizeInPixel),
startIndexOfPath,
startIndexOfPath + path.length,
0
)
spannable.setSpan(
ForegroundColorSpan(Color.parseColor(colorCode)),
startIndexOfPath,
startIndexOfPath + path.length,
0
)


return spannable
}

使用

text_view.text = "A B C D".setFontSizeForPath("B",30)
private SpannableString getFormattedText(String textToBold, String normalText, boolean boldTextFirst) {
String result = boldTextFirst ? textToBold + normalText : normalText + textToBold;
SpannableString str = new SpannableString(result);


Typeface typeface = ResourcesCompat.getFont(requireContext(), R.font.product_sans_bold);
int style = typeface != null ? typeface.getStyle() : Typeface.BOLD;


int textToBoldStartIndex = str.toString().indexOf(textToBold);
str.setSpan(new StyleSpan(style), textToBoldStartIndex, textToBoldStartIndex + textToBold.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


int normalTextStartIndex = str.toString().indexOf(normalText);
str.setSpan(new AbsoluteSizeSpan(13, true), normalTextStartIndex, normalTextStartIndex + normalText.length(), 0);
return str;
}