繁体   English   中英

如何在 Android 中以编程方式更改字体大小?

[英]How to change font size programmatically in Android?

我需要在运行时更改应用程序的字体大小。 我参考了以下SO 帖子,其中他们谈到通过 style.xml 应用字体大小并应用它。 我认为它仅适用于特定元素(如 TextView 或布局),但是否可以在应用程序级别应用字体大小,是否可以以编程方式设置?

获取您的文本视图TextView textView setTextSize(size)并应用setTextSize(size)

textView.setTextSize(20);

请注意,大小以像素为单位,而不是 style.xml 布局中的dp

是的,设置文字大小是:

textView.setTextSize(20)// text size

在这里添加了更多东西:)

1.如果你想设置为DP

textView.setTextSize(coverPixelToDP(20));
    
private int coverPixelToDP (int dps) {
    final float scale = this.getResources().getDisplayMetrics().density;
    return (int) (dps * scale);
}

2.如果你想自动调整字体大小以适应边界使用,

setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)

JAVA版

TextView textView = new TextView(this);
textView.setText("Adjust font size for dynamic text");
//only works when width = 'match_parent', and give height
LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 500); 
           
textView.setLayoutParams(p1);
textView.setAutoSizeTextTypeUniformWithConfiguration(8, 15, 1, TypedValue.COMPLEX_UNIT_DIP); 

XML 版本(以编程方式)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <TextView
      android:layout_width="match_parent" // make sure it is match_parent
      android:layout_height="500dp" //make sure you give height 
      app:autoSizeTextType="uniform"
      app:autoSizeMinTextSize="12sp"
      app:autoSizeMaxTextSize="100sp"
      app:autoSizeStepGranularity="2sp" />

</LinearLayout>

暂无
暂无

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

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