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

4

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


这个回答解决了你的问题吗?如何在整个应用程序中以编程方式更改字体大小,Android? - Mohamed Nageh
2个回答

4

拿出你的文本视图TextView textView,并应用setTextSize(size)

textView.setTextSize(20);

请注意,此处的尺寸单位为像素(px),而非在styles.xml布局中使用的dp单位。

2

是的,设置文本大小是:

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接