Różne rozmiary czcionek ciągów w tym samym widoku tekstowym

Mam textView wewnątrz z liczbą (zmienną) i string, Jak mogę dać liczbę o jeden rozmiar większą niż string? kod:

TextView size = (TextView)convertView.findViewById(R.id.privarea_list_size);
if (ls.numProducts != null) {
    size.setText(ls.numProducts + " " + mContext.getString(R.string.products));
}
Chcę ls.numproducts ma rozmiar inny niż reszta tekstu. Jak to zrobić?
Author: AskNilesh, 2013-05-02

10 answers

Użyj 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); 

Snap shot

Tutaj wpisz opis obrazka

Możesz podzielić ciąg za pomocą spacji i dodać span do wymaganego ciągu.

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

Teraz Zastosuj span do string i dodaj to samo do textview.

 375
Author: Raghunandan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-11 11:32:04

Jeśli zastanawiasz się, jak ustawić wiele różnych rozmiarów w tym samym widoku tekstu, ale używając rozmiaru bezwzględnego, a nie względnego, możesz to osiągnąć za pomocą AbsoluteSizeSpan zamiast RelativeSizeSpan.

Po prostu uzyskaj wymiar w pikselach żądanego rozmiaru tekstu

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

A następnie utwórz nową AbsoluteSpan na podstawie tekstu

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);
 127
Author: Joao Sousa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-15 14:08:54

Możesz to zrobić używając ciągu html i ustawiając html na Textview używając
txtView.setText(Html.fromHtml("Your html string here"));

Na przykład:

txtView.setText(Html.fromHtml("<html><body><font size=5 color=red>Hello </font> World </body><html>"));`
 8
Author: Remmyabhavan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-04 08:16:19

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

Użycie

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

Tutaj wpisz opis obrazka

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

Użycie

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

Tutaj wpisz opis obrazka

 7
Author: Phan Van Linh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-17 02:09:57
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));

---------------- wynik ---------------

Wynik:

12345.24

 4
Author: Anandharaj R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-22 12:49:44

Spróbuj spannableStringbuilder . Za jego pomocą możemy utworzyć ciąg znaków o wielu rozmiarach czcionek.

 3
Author: PgmFreek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-02 10:04:39

Najlepszym sposobem na to jest Html bez podcięcia tekstu i w pełni dynamiczny Na przykład:

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

    }

I możesz użyć atrybutu koloru itp... jeżeli druga ręka :

size.setText(Html.fromHtml(getTextSize(ls.numProducts,100) + " " + mContext.getString(R.string.products));  
 3
Author: Garci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-14 14:50:35

Napisałem własną funkcję, która zajmuje 2 stringi i 1 int (rozmiar tekstu)

Pełny tekst i część tekstu, którą chcesz zmienić jego rozmiar.

Zwraca SpannableStringBuilder, którego można użyć w widoku tekstowym.

  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;
    }
 2
Author: Ali Asadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-13 12:25:25

W przypadku, gdy chcesz uniknąć zbyt wiele zamieszania dla swoich tłumaczy, wymyśliłem sposób, aby mieć tylko symbol zastępczy w ciągach, które będą obsługiwane w kodzie.

Więc, jeśli masz to w strunach:

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

I chcesz, aby tekst zastępczy miał inny rozmiar i kolor, możesz użyć tego:

        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

I wynik:

Tutaj wpisz opis obrazka

 0
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-23 11:56:21

W kotlinie zrób to jak poniżej używając html

HtmlCompat.fromHtml("<html><body><h1>This is Large Heading :-</h1><br>This is normal size<body></html>",HtmlCompat.FROM_HTML_MODE_LEGACY)
 -2
Author: Shashank Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-17 08:13:20