164

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

4

12 回答 12

404

用一个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); 

快照

在此处输入图像描述

您可以使用空格拆分字符串并将跨度添加到您需要的字符串。

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

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

于 2013-05-02T10:10:41.397 回答
143

以防万一您想知道如何在同一个文本视图中设置多个不同的大小,但使用绝对大小而不是相对大小,您可以使用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);
于 2015-01-27T15:58:16.030 回答
10

您可以使用 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>"));`
于 2013-05-02T10:01:54.743 回答
8

方法一

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

在此处输入图像描述

方法二

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

在此处输入图像描述

于 2017-11-17T02:09:57.397 回答
5
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. 24

于 2018-06-07T09:38:57.847 回答
4

做到这一点的最好方法是 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));  
于 2019-02-14T14:50:35.233 回答
3

尝试spannableStringbuilder。使用它,我们可以创建具有多种字体大小的字符串。

于 2013-05-02T10:04:39.720 回答
2

我编写了自己的函数,它需要 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;
    }
于 2018-02-13T12:25:25.147 回答
0

如果您想避免给翻译人员造成太多混乱,我想出了一种在字符串中仅包含一个占位符的方法,该占位符将在代码中进行处理。

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

    <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

结果:

在此处输入图像描述

于 2020-04-23T11:56:21.547 回答
0

kotlin 爱好者的 Utils 方法

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)
于 2021-08-03T08:02:57.460 回答
0
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;
}
于 2022-01-23T01:34:42.990 回答
-3

在 kotlin 中,使用 html 执行如下操作

HtmlCompat.fromHtml("<html><body><h1>This is Large Heading :-</h1><br>This is normal size<body></html>",HtmlCompat.FROM_HTML_MODE_LEGACY)
于 2020-08-09T17:59:54.283 回答