Android TextView.setTextSize 行为异常 - 如何为不同屏幕动态设置 textview 的文本大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3687065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:21:57  来源:igfitidea点击:

TextView.setTextSize behaves abnormally - How to set text size of textview dynamically for different screens

androidtextview

提问by singhspk

Calling TextView.setTextSize()is working abnormally. Right after the call to setTextSizeif we get a getTextSizeits returning a much higher value that what we set it to earlier.

呼叫TextView.setTextSize()工作异常。在调用setTextSizeif之后,getTextSize它返回一个比我们之前设置的值高得多的值。

Here's what we're doing:

这是我们正在做的事情:

zoomControl.setOnZoomInClickListener(new OnClickListener() {
    public void onClick(View view) {
        float size = mViewShabad.getTextSize() + 1;
        textView.setTextSize(size);
    }
});

Has anyone seen this before?

有没有人见过这个?

回答by Kevin Coppock

The difference here is that in the setTextSize(int size)method, the unit type by default is "sp" or "scaled pixels". This value will be a different pixel dimension for each screen density (ldpi, mdpi, hdpi).

这里的区别在于,在setTextSize(int size)方法中,单位类型默认为“sp”或“缩放像素”。对于每个屏幕密度(ldpi、mdpi、hdpi),此值将是不同的像素尺寸。

getTextSize(), on the other hand, returns the actual pixel dimensions of the text.

getTextSize(),另一方面,返回文本的实际像素尺寸。

You can use setTextSize(int unit, float size)to specify a unit type. The constant values for this can be found in the TypedValue class, but some of them are:

您可以使用setTextSize(int unit, float size)来指定单位类型。这个常量值可以在 TypedValue 类中找到,但其中一些是:

TypedValue.COMPLEX_UNIT_PX   //Pixels

TypedValue.COMPLEX_UNIT_SP   //Scaled Pixels

TypedValue.COMPLEX_UNIT_DIP  //Device Independent Pixels

回答by M_AWADI

this problem happend because the getTextSize()method return the size in pixels depend on screen density ! to get the Actual TextSize use this :

发生此问题是因为该getTextSize()方法返回的像素大小取决于屏幕密度!要获得实际的 TextSize 使用这个:

DisplayMetrics metrics;
metrics = getApplicationContext().getResources().getDisplayMetrics();
float Textsize =myTextView.getTextSize()/metrics.density;
myTextView.setTextSize(Textsize+1);

i hope it solve it :)

我希望它解决它:)

回答by u4327805

if Setting change font size,something cause show error,you can do as:

如果设置改变字体大小,导致显示错误,你可以这样做:

setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15.f);

回答by ranjan

When we try to setText() programmitically problem with getTextSize(), returns value in px instead of sp/dp/dip and we know 1sp/dp=1.5px(screen size =240).

当我们尝试使用 getTextSize() 以编程方式解决 setText() 问题时,返回值以 px 而不是 sp/dp/dip 为单位,我们知道 1sp/dp=1.5px(屏幕尺寸 =240)。

 titleBar.setTextSize(TypedValue.COMPLEX_UNIT_SP, (getResources().getDimension(R.dimen.text_size)*1.5f)); 

is working perfectly for me or we can use displaymatrix to px:sp/dp ratio then replace that value with 1.5f

对我来说效果很好,或者我们可以使用 displaymatrix 到 px:sp/dp 比率,然后用 1.5f 替换该值

means-> titleBar.setTextSize(TypedValue.COMPLEX_UNIT_SP, (getResources().getDimension(R.dimen.text_size)*your_sp_and_px_ratio_in_int f));

回答by NagarjunaReddy

After long time struck this and finally solved like this

经过很长时间的打击,终于像这样解决了

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
          getResources().getDimension(R.dimen.textsize));

create dimen folder like this res/values/dimensions.xml

创建像这样的尺寸文件夹 res/values/dimensions.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

 <dimen name="textsize">8sp</dimen>

 </resources>

回答by Frank Nguyen

In short, if you want to zoom out your textsize

简而言之,如果你想缩小你的文字大小

float size = mViewShabad.getTextSize()*1.1f;
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);

Because getTextSize() return UNIT_PX, then we should use UNIT_PX

因为 getTextSize() 返回 UNIT_PX,那么我们应该使用 UNIT_PX

回答by Kevin Grant

Adding some extra flavor for this answer, as also ran into a bit of confusion. You shouldbe able to drop this test into any @RunWith(AndroidJUnit4.class)test you have in your project (you'll also need to add the dimens to your dimens.xml).

为这个答案添加一些额外的味道,因为也遇到了一些混乱。您应该能够将此测试放入@RunWith(AndroidJUnit4.class)您项目中的任何测试中(您还需要将尺寸添加到您的 dimens.xml)。

Note: All these tests pass

注意:所有这些测试都通过

@Test public void testScaledFontSizes() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    final Context context = InstrumentationRegistry.getTargetContext();

    Configuration configuration = context.getResources().getConfiguration();
    configuration.fontScale = 2.0f;
    configuration.densityDpi = 160; // mdpi, 1:1
    context.getResources().updateConfiguration(configuration, null);

    float scaledTextSize = context.getResources().getDimensionPixelSize(R.dimen.sp_15);
    assertEquals(30.0f, scaledTextSize);

    // Create a new TextView with the explicitly set configuration
    TextView textView = new TextView(context);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, scaledTextSize);

    // 30, because font size is scaled
    assertEquals(30.0f, textView.getTextSize());

    // This is what we *don't* want, it's scaled *twice*!
    textView.setTextSize(scaledTextSize);
    assertEquals(60.0f, textView.getTextSize());

    // DP instead of SP tests
    float fifteenDp = context.getResources().getDimensionPixelSize(R.dimen.dp_15);
    assertEquals(15.0f, fifteenDp);

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fifteenDp);
    // Still 15, because it's DP, not SP
    assertEquals(15.0f, fifteenDp);

    textView.setTextSize(fifteenDp);
    // 30, because setTextSize DOES font scaling
    assertEquals(30.0f, textView.getTextSize());
  }
}

The big takeaway I found is that TextView.setTextSize(float)applies the font scaling, so if you pass in a dimen thats already labelled as SP instead of DP, then it will receive the font scaling twice.

我发现的最大收获是TextView.setTextSize(float)应用了字体缩放,所以如果你传入一个已经标记为 SP 而不是 DP 的尺寸,那么它将接收字体缩放两次

回答by Gibolt

Kotlin Solution

科特林解决方案

To set using a resource, just use this:

要使用资源进行设置,只需使用以下命令:

textView.setTextSize(COMPLEX_UNIT_PX, textView.resources.getDimension(R.dimen.my_text_size))

To do the same with a resource value, add this extension property to much more easily set your text size

要对资源值执行相同操作,请添加此扩展属性以更轻松地设置文本大小

textView.textSizeRes = R.dimen.my_text_size

var TextView.textSizeRes
    get() = textSize.toInt()
    set(@DimenRes textSizeRes) {
        setTextSize(COMPLEX_UNIT_PX, resources.getDimension(textSizeRes))
    }