Getting the Text Size of a Spannable TextView

Viewed 1745

I have a button which increases the size of selected text when clicked. I want it to increase to a certain size, e.g. 36sp, then after that, it stops. I am using a RelativeSizeSpan for this. text.getTextSize() seems to be returning a constant value, which looks like the default/overall size. How can I get the size of the selected Text?

private void makeChanges(float size) {
    Log.d("EditText", "makeChanges Text Size: " + text.getTextSize());

    str.setSpan(new RelativeSizeSpan(size),
                    selectionStart, selectionEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.setText(str);
}
1 Answers

If you look closer at your code you can notice that RelativeSizeSpan receives a float value, which increases the size of your text by a that given percentage. The default value is in pixels. If you need the modified size, you need to get the default value and multiply it by float size variable. If that factor changes during runtime, you can access it the with following methods

The following code is a demonstration, tweak it for your use. It is tested with a debugger and it shows correct value.

    SpannableString ss = new SpannableString("some nice text goes here.");
    ss.setSpan(new RelativeSizeSpan(3.0f), 5, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    TextView tView = findViewById(R.id.textView);

    tView.setText(ss);

    // default size - before span
    int pixelsPrevious = (int) tView.getTextSize();

    // spanned text
    Spanned spanned = (Spanned) tView.getText();
    RelativeSizeSpan[] spanArray = spanned.getSpans(0, spanned.length(), RelativeSizeSpan.class);

    // you are looking for this value.
    int pixelsNew = (int) (pixelsPrevious * spanArray[0].getSizeChange());
Related