Android TextView setTextSize incorrectly increases text size [duplicate]
Asked Answered
G

3

53

This is in an extension of TextView. getTextSize() and setTextSize() are not overridden, I do not extend those methods. Programming in 1.6, API level 4.

The loop in this code causes size to be multiplied by 1.5 every time it iterates, e.g. if size initially reads 200 from getTextSize, then setTextSize(size) is called, getTextSize called again reads back 300.

public void shrinkTest() {
    float size = this.getTextSize(); 
    while (size > 8) {
        this.setTextSize(size);
        size = this.getTextSize();
    }
}

Why is this?

Ginsberg answered 17/2, 2011 at 17:28 Comment(0)
J
163

Heh, mixed units problem. Seems a little counterintuitive, but it's an easy fix. The default method setTextSize(float) assumes you're inputting sp units (scaled pixels), while the getTextSize() method returns an exact pixel size.

You can fix this by using the alternate setTextSize(TypedValue, float), like so:

this.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);

This will make sure you're working with the same units.

Jone answered 17/2, 2011 at 17:34 Comment(0)
I
23

setTextSize() and getTextSize() work with different units. The parameter to set() is density-independent "scaled pixels", whereas get() returns plain old pixels.

Identity answered 17/2, 2011 at 17:33 Comment(1)
Hah, thought that only ever happened to me! Have an upvote for your slightly more useful answer...Identity
U
5

pass units with size using TypedValue like below:

TypedValue.COMPLEX_UNIT_PX //Pixels

TypedValue.COMPLEX_UNIT_SP //Scaled Pixels

TypedValue.COMPLEX_UNIT_DIP //Device Independent Pixels

setTextSize(TypedValue.COMPLEX_UNIT_SP, 18)

Unbelievable answered 23/6, 2016 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.