SpannableString does not work

1

Hello good morning I have a question with the SpannableString class of android, I am very new with this class and also my knowledge related to when something works for an api or not or what api should choose are limited.

I have this piece of code in my onCreate () method:

    String texto = "Texto para usar";

    Spannable timeSpannable = new SpannableString(texto.toUpperCase());

    boton.setText(timeSpannable);

This does not work, to make sure I have given another use to the Spannable class and I have tried this method that I found in this same forum in English:

public static SpannableString highlight(String s, int k) {
    SpannableString ss = new SpannableString(s);
    ss.setSpan(new ForegroundColorSpan(Color.BLUE), 0, k, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);


    return ss;
}

Then I'll call it on onCreate () so that my program code looks like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    Button boton = (Button) findViewById(R.id.ir);

    boton.setText("Texto para usar");

    boton.setLayoutParams(layoutparams);

    boton.setText(highlight(boton.getText().toString(),3));
}

That does not work either, my question is: is there something I'm doing wrong? Is there any kind of restriction when using the Spannable class in any specific API, and how should I modify my code to make it work?

The minimum api of my project is 15: iceCreamSandwich.

The api of my mobile phone is the 22nd one where I test the application.

    
asked by Reductor 23.09.2017 в 14:54
source

1 answer

1

Spannable has a problem with the allCaps function.

That, combined with the fact that from Android 5.0 the buttons bring by default allCaps activated, as part of the standard Material Design :

  

Button text should be capitalized in languages that have   capitalization For other languages, colored text on flat buttons   distinguishes them from normal text.

It will cause the texts of Spannable not to work.

Above, in your code, you convert the text into a capital letter, which is not necessary.

Solution 1:

Remove AllCaps of the button from Java:

String texto = "Texto para usar";
Spannable timeSpannable = new SpannableString(texto);
boton.setAllCaps(false);
boton.setText(timeSpannable);

Solution 2:

Remove allCaps from the button layout:

<Button
    ...
    android:allCaps="false" />

Try this way and see if it works.

For more details you can see this SO answer in English .

    
answered by 23.09.2017 / 16:19
source