Inconsistency when setting TextView font size in code and in resources

前端 未结 3 688
清歌不尽
清歌不尽 2020-12-23 08:56

The official documentation does not seem to answer this, or I can\'t figure it out.

Element (nevermind the AlertDialog, it happens on any TextView as we

相关标签:
3条回答
  • 2020-12-23 09:36

    You should use setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); because the documentation of the getDimension method states that it returns a Resource dimension value multiplied by the appropriate metric. which I understand to be the precalculated absolute px value.

    That is, use:

    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size_small));
    
    0 讨论(0)
  • 2020-12-23 09:41

    Somehow this seems to fit:

    XML:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <dimen name="typo14">9sp</dimen>
    </resources>
    

    Java:

    setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
    setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.typo14));
    
    0 讨论(0)
  • 2020-12-23 09:56

    Its a matter of sp px dpi

    tv.setTextSize(14) = 14 pixels 
    
    0 讨论(0)
提交回复
热议问题