Reputation: 13
Emulator 1:
Emulator 2
How can I keep the same text size on button on different emulator? I am using these lines of code to set a relative size that keeps the ratio, but when I run the program on 2 different emulators (real emulators) the text gets crazy sizes
Code Snippets
btn_play_game1.post(new Runnable() {
@Override
public void run() {
btn_play_game1.setTextSize((float) (btn_play_game1.getHeight() * btn_play_game1.getWidth() * 0.00013));
}
});
Also I am using LinearLayout in my xml
files, If that matters.
Upvotes: 0
Views: 126
Reputation: 19524
You're calling setTextSize(float)
:
Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.
Assuming both emulators are set to the same system font size (which will also make the text bigger or smaller) the issue is that you're already providing a final scaled size, by taking the button's dimensions in pixels. But that method is expecting a size in sp
, a density-independent size that will be scaled according to the device's screen density and the user's font preferences. So the higher the screen resolution, the more it's getting scaled up
Here's three options:
sp
value to use (depending on how big the text should look, try 24 and go from there) - again this will be bigger or smaller depending on the user's prefsTypedValue.COMPLEX_UNIT_PX
for the first parameter, and your calculated-from-the-pixels size as the second. That way the text size will always be proportional to your button size the way you're calculating it, and the user's font size prefs don't come into it. You'll have to change that 0.00013
value because that's just what happened to work when you were passing a sp
valuedp
value instead of sp
if you want it to take up a fixed amount of space (no user scaling) - some text doesn't need to scaleAlso that's a weird way of calculating a ratio, I think in this situation you'd generally just take a fraction of the height for consistency, or do something with minOf(height, width)
if the width is variable - but then you're getting into the complexity of measuring the text to see what it needs to fit, and it's way easier to just let the layout system handle all that. There's a bunch of ways you could do it in XML, but that's another story
Upvotes: 2