简体   繁体   English

以编程方式自动调整按钮文本大小

[英]Autosizing button text programmatically

I'm creating buttons programmatically and the text is slightly cut-off.我正在以编程方式创建按钮,文本略有截断。 I trying to autosize the text-size but I've only found how to do so in XML:我试图自动调整文本大小,但我只在 XML 中找到了如何做到这一点:

app:autoSizeTextType="uniform"

but have to to do programmatically and can't figure out how to do so with a button and not a TextView.但必须以编程方式进行,并且无法弄清楚如何使用按钮而不是 TextView。 I tried the following line:我尝试了以下行:

letter.setAutoSizeTextTypeUniformWithConfiguration(10, 100,2, TypedValue.COMPLEX_UNIT_SP);

but it doesn't do anything.但它什么也没做。

This is how my buttons are created, the width depends on the screen width:这就是我的按钮的创建方式,宽度取决于屏幕宽度:

Button letter = new Button(context);
LinearLayout.LayoutParams btnlp = new LinearLayout.LayoutParams(dpWidth/10-2, LinearLayout.LayoutParams.WRAP_CONTENT);
            btnlp.setMargins(1,15,0, 0);

Using Sample xml.使用样品 xml。 You don't need to program.你不需要编程。

android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="12sp"
android:autoSizeMaxTextSize="100sp"
android:autoSizeStepGranularity="2sp"

there is a related method setAutoSizeTextTypeWithDefaults , but is available starting API26, so I would advice you to use more universal TextViewCompat有一个相关的方法setAutoSizeTextTypeWithDefaults ,但从 API26 开始可用,所以我建议你使用更通用的TextViewCompat

TextViewCompat.setAutoSizeTextTypeWithDefaults(textView, 
    TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM