Ryan Daily
Ryan Daily

Reputation: 33

Android text over-enlarging text size

I'm new to android and I'm working on this "About" page that is giving me some really weird behavior. It has text that when clicked expands and then collapses when clicked again. The collapsed text is of a larger size than the expanded text. When I click to expand, the text is waaay larger than even the larger expanded text and even when I go to collapse again the collapsed text keeps the huge text size too. (It changes the actual text content just fine)

The xml Textview

<TextView
            ...
            android:textSize="@dimen/About_filler"
            android:id="@+id/Stuff"
            android:text="@string/about_filler"
            android:clickable="true"
            android:onClick="collapseToggle"
            ...
/>

The method clicking calls

public void collapseToggle(View view){
    TextView text = (TextView) view;
    if( ! text.getText().equals(getString(R.string.about_filler))){ //if not collapsed
        text.setText(getString(R.string.about_filler));
        text.setTextSize(getResources().getDimension(R.dimen.About_filler));
    }

    else if(text.getId() == R.id.Stuff){
        text.setText(getString(R.string.about_contents_Stuff));    
        text.setTextSize(getResources().getDimension(R.dimen.About_contents));
    }

And the dimen folder

...
<dimen name="About_contents">20sp</dimen>
<dimen name="About_filler">40sp</dimen>

I know there are a million better ways to implement this kind of thing but why this is happening is just killing me.

Upvotes: 2

Views: 78

Answers (1)

Vesko
Vesko

Reputation: 3760

By default text.setTextSize(float size) assumes you're passing the size in SP units, thus it's converting the SP to PX internally.

On the other hand getResources().getDimension() is returning the unit in PX, internally doing the conversion from whatever value you set.

So what's happening in your case

  • you've set 20sp in the dimens.xml
  • getDimension() is returning say 100px (depending on the screen)
  • setTextSize() assumes you've set 100sp and resizes it to something really HUUGE.

To fix just use the other option for setTextSize() that accepts units: text.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.About_contents));

Upvotes: 1

Related Questions