Android set TextView text size to look the same on

2019-08-17 04:35发布

问题:

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 the Images and Texts are being arranged using the general gravity and layout_gravity values. Here is a small sample:

Here is my problem: I want the SAMPLE TEXT to look exactly the same size on all screen sizes, being a phone of 480p or a tablet of 1200p. Initially I thought that setting the text size in SP will be enought but it is not, because as screen resolution gets bigger, the text gets smaller.

So my question is, how can I programatically set the text size so it will look exactly of the same size, independent of screen width. As you can see the parent layout will always be a square.

I tried programatically setting SP or using a scale factor.

float scale = 0;

if (screenWidth == 720) {
        scale = 1;
} else {
        scale = (720 - screenWidth) * 100.2f / screenWidth;
}

float defaultSizeFor720 = 35f;

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, defaultSizeFor720 * scale);

It does not work. as screen gets bigger, text gets smaller, not as small as when only using SP alone, but still. I also tried most of the answers from other questions but still did not work. Any ideas?

回答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

    float DEFAULT_SCREEN_WIDTH = 720f;
    
    float TEXT_HEIGHT = 50f;
    float sizeLine1 = (screenWidth * TEXT_HEIGHT) / DEFAULT_SCREEN_WIDTH;
    Rect bounds = new Rect();
    int textSize = 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.



回答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.