【问题标题】:Different font size of strings in the same TextView同一TextView中字符串的不同字体大小
【发布时间】:2013-04-26 10:56:56
【问题描述】:

我有一个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 的大小与文本的其余部分不同。怎么办?

【问题讨论】:

    标签: android string textview text-size


    【解决方案1】:
    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;
    }
    

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        【解决方案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)
        

        【讨论】:

        • 使用fromHtml() 方法会导致性能问题,这不是最佳实践。
        【解决方案4】:

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

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

            <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
        

        结果:

        【讨论】:

          【解决方案5】:

          做到这一点的最好方法是 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));  
          

          【讨论】:

            【解决方案6】:
            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

            【讨论】:

              【解决方案7】:

              使用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

              【讨论】:

              • setSpan() return: java.lang.IndexOutOfBoundsException: setSpan (0 ... 5) ends beyond length 1. 这是什么意思?
              • 检查字符串的长度。 IndexOutOfBoundsException:指示跨度开始和结束的索引位置错误。在上面的 Hello 长度是 5 所以我应用了从索引 0 到 5 的跨度
              • 完美地在谷歌眼镜上工作!
              • 有没有办法将小的字符在垂直方向移动到中心?基本上所有字符都应该垂直居中,不管大小。
              • 在这种情况下您可能需要两个文本视图,否则您需要制作自己的文本视图
              【解决方案8】:

              如果您想知道如何在同一个 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);
              

              【讨论】:

              • AbsoluteSizeSpan 示例很好的补充
              • @AmitGarg 你想详细说明一下吗?
              • 也可以使用AbsoluteSizeSpan(sizeInDip, true)直接在dp中指定大小
              【解决方案9】:

              我已经编写了自己的函数,它需要 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;
                  }
              

              【讨论】:

                【解决方案10】:

                方法一

                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
                

                【讨论】:

                  【解决方案11】:

                  您可以使用 html 字符串并使用
                  txtView.setText(Html.fromHtml("Your html string here"));

                  将 html 设置为 Textview 来完成此操作

                  例如:

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

                  【讨论】:

                  • 不错的贡献!但是 fromHtml 从现在开始(API >= N)已被弃用。为此,请执行此操作以允许兼容模式: if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { txtView.setText(Html.fromHtml("your html string ")), Html.FROM_HTML_MODE_LEGACY)); } else { txtView.setText(Html.fromHtml("你的 html 字符串")); }
                  • “5”的单位是什么?是dp吗?是 sp 吗?我怎样才能将其更改为其中任何一个?
                  • 颜色和家庭作品,但是尺寸不起作用。
                  【解决方案12】:

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

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-03-12
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-01-29
                    • 2020-03-01
                    相关资源
                    最近更新 更多