3

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);
}
shizhen
  • 12,251
  • 9
  • 52
  • 88
Prox
  • 639
  • 10
  • 15
  • 1
    That is because `getTextSize()` returns the default value for the `TextView`. What are you expecting to get? – Barns Dec 28 '18 at 01:05
  • Because you are using `RelativeSizeSpan` I do not think that you can get an absolute size like "36sp". You will need to do the math yourself. If you were to use `AbsoluteSizeSpan` then you could get the absolute size of the selected text. – Barns Dec 28 '18 at 01:27
  • @Barns I want to get the text size of the currently selected text by the user, as a result, limit them to how much they can increase the text – Prox Dec 29 '18 at 00:19
  • @Barns I want the user to increase the text size and decrease it how ever they want. From my understanding of `AbsoluteSizeSpan` it sets fixed sizes. This was my initial approach, to set a global variable and add to it when ever the user increases the size and decrease it otherwise. The problem I encountered is that the global variable remains the same even if the selected text changes. Then I decided to use `RelativeSizeSpan`. – Prox Dec 29 '18 at 00:25

1 Answers1

1

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());
N. Matic
  • 213
  • 1
  • 8