Skip to content Skip to sidebar Skip to footer

Android Set Textview Text Size To Look The Same On All Screen Sizes

I have a square LinearLayout containing a few other LinearLayouts with ImageViews and TextViews inside. I am saving the layout content as png file after the user changes it. All th

Solution 1:

The only reliable method I found was:

  • have a text height for a default screen size
  • scale this text height based on current screen size
  • find the best match in text size to fit the needed height

    floatDEFAULT_SCREEN_WIDTH=720f;
    
    floatTEXT_HEIGHT=50f;
    floatsizeLine1= (screenWidth * TEXT_HEIGHT) / DEFAULT_SCREEN_WIDTH;
    Rectbounds=newRect();
    inttextSize=1;
    while (bounds.height() < sizeLine1) {
        textSize++;
        txtLine1.getPaint().setTextSize(textSize);
        txtLine1.getPaint().getTextBounds("test", 0, "test".length(), bounds);
    }
    

Might not be elegant or efficient, but it is acceptable, and does work. There are minor differences between tablet 1200p and 480p phones, but these are OK in my case.

Solution 2:

Remove text size attribute from TextView tag in your xml file and try this in code

float textSize = getResources().getDimension(R.dimen.textsize) / getResources().getDisplayMetrics().density;
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
textView.setText(" Your desired text ");

Hope this will help you.

Post a Comment for "Android Set Textview Text Size To Look The Same On All Screen Sizes"