[android] Different font size of strings in the same TextView

I have a textView inside with a number (variable) and a string, how can I give the number one size larger than the string? the code:

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

I want ls.numproducts has a size different from the rest of the text. How to do?

This question is related to android string textview text-size

The answer is


In case you want to avoid too much confusion for your translators, I've come up with a way to have just a placeholder in the strings, which will be handled in code.

So, supposed you have this in the strings:

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

And you want the placeholder text to have a different size and color, you can use this:

        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

And the result:

enter image description here


I have written my own function which takes 2 strings and 1 int (text size)

The full text and the part of the text you want to change the size of it.

It returns a SpannableStringBuilder which you can use it in text view.

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

in kotlin do it as below by using html

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

Try spannableStringbuilder. Using this we can create string with multiple font sizes.


You can get this done using html string and setting the html to Textview using
txtView.setText(Html.fromHtml("Your html string here"));

For example :

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

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

using

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

enter image description here

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

using

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

enter image description here


Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan instead of a RelativeSizeSpan.

Just get the dimension in pixels of the desired text size

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

and then create a new AbsoluteSpan based on the text

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

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

---------------- Result ---------------

Result :

12345.24


The best way to do that is Html without substring your text and fully dynamique For example :

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

    }

and you can use color attribut etc... if the other hand :

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

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to textview

Kotlin: How to get and set a text to TextView in Android using Kotlin? How to set a ripple effect on textview or imageview on Android? The specified child already has a parent. You must call removeView() on the child's parent first (Android) Android: Creating a Circular TextView? android on Text Change Listener Android - Set text to TextView Placing a textview on top of imageview in android Rounded corner for textview in android Different font size of strings in the same TextView Auto-fit TextView for Android

Examples related to text-size

Text size of android design TabLayout tabs Different font size of strings in the same TextView Text size and different android screen sizes What is the default text size on Android? How to assign text size in sp value using java code Inline elements shifting when made bold on hover