If I set the font size directly in xml, then everything is displayed normally.

android:textSize="@dimen/textMM" 

If I set it programmatically, the font is huge:

 actFontSize = getResources().getDimension(R.dimen.textMM); btn.setTextSize(actFontSize); 

I have a few dimens.xml with sizes depending on the width of the screen. Whether in a software task, he takes it from another folder, or I’ve got it somewhere.

    2 answers 2

    There are 2 methods to set the font size:

    • setTextSize(float size) simplified installation method
    • setTextSize(int complex_unit, float size) complete installation method

    The first (simple) method always calls the second (full) method and passes the input size to COMPLEX_UNIT_PX .

    You have a mismatch between xml and java only in the type of measure. To fix the problem, use the full-fledged method by passing there your type of measure from xml .

    Possible values for complex_unit

    For example, for a size specified in sp units, use the constant:

    TypedValue.COMPLEX_UNIT_SP

    • I allowed myself to add a little to your answer - pavlofff
    • Thanks a lot :) - zTrap
    • I tried: btn.setTextSize (TypedValue.COMPLEX_UNIT_SP, actFontSize); Nothing has changed :(. - lmihael
    • Displayed on the console System.out.println (actFontSize); - I get 120.0 And in xml it costs 50sp! - lmihael
    • All figured out - it was necessary to set the size in pixels. - lmihael

    Thank you very much zTrap and pavlofff. Long stupid but finally figured out.

     actFontSize = getResources().getDimension(R.dimen.textMM); 

    Converts the size in SP to the size in pixels. Therefore, it turns out 50SP turns into 120PX. Therefore, when installing

    btn.setTextSize(TypedValue.COMPLEX_UNIT_PX,actFontSize);

    It is necessary to put UNIT_PX pixels.