如何在Android应用程序中通过编程方式改变整个应用程序的字体大小?

24

我已创建了一个Spinner,其中包含字号从“8”到“46”的列表。我能够点击字体大小,在下拉列表中显示出来。

我的需求是,如果我在Spinner中点击字号“26”,则应将其应用于整个项目,例如应用于屏幕、TextView的外观、EditText-粗体/斜体等。再次,如果我点击46号字体,则应将其应用于整个项目。

我如何通过编程实现这一点?


1
我猜你想创建一些偏好设置,以便在整个应用程序中更改文本大小。你可以为此创建样式。http://developer.android.com/guide/topics/ui/themes.html - Siddharth Lele
但是动态地不使用样式和主题。我该怎么做呢?有什么想法!!! - Achiever
这回答解决了你的问题吗?Android:我如何为布局设置文本大小? 答案正是你所需要的。 - Marian Paździoch
6个回答

33

Android文档没有明确说明如何在应用程序级别通过用户选择最有效地全局更改字体大小。

我认为Black Devil给出的答案存在问题。

问题在于许多Android小部件都是TextView子类,例如ButtonRadioButtonCheckBox。其中一些是TextView的间接子类,这使得在这些类中实现自定义版本的TextView非常困难。

然而,正如Siddharth Lele在他的评论中指出的那样,使用stylesthemes是处理整个应用程序中的文本大小变化的更好方法。

我们设置布局样式来控制视图的外观和感觉。主题本质上只是这些样式的集合。但是,我们可以仅对文本大小设置使用主题,而无需为每个属性定义值。使用主题而不是样式提供了一个巨大的优势:我们可以以编程方式为整个视图设置主题。

theme.xml

<resources>
    <style name="FontSizeSmall">
        <item name="android:textSize">12sp</item>
    </style>
    <style name="FontSizeMedium">
        <item name="android:textSize">16sp</item>
    </style>
    <style name="FontSizeLarge">
        <item name="android:textSize">20sp</item>
    </style>
</resources>

创建一个类来处理加载我们的偏好设置:

public class BaseActivity extends Activity {
    @Override
    public void onStart() {
        super.onStart();

        // Enclose everything in a try block so we can just
        // use the default view if anything goes wrong.
        try {
            // Get the font size value from SharedPreferences.
            SharedPreferences settings =
                getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE);

            // Get the font size option.  We use "FONT_SIZE" as the key.
            // Make sure to use this key when you set the value in SharedPreferences.
            // We specify "Medium" as the default value, if it does not exist.
            String fontSizePref = settings.getString("FONT_SIZE", "Medium");

            // Select the proper theme ID.
            // These will correspond to your theme names as defined in themes.xml.
            int themeID = R.style.FontSizeMedium;
            if (fontSizePref == "Small") {
                themeID = R.style.FontSizeSmall;
            }
            else if (fontSizePref == "Large") {
                themeID = R.style.FontSizeLarge;
            }

            // Set the theme for the activity.
            setTheme(themeID);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

最后,通过扩展BaseActivity创建活动,就像这样:

public class AppActivity extends BaseActivity{
}

由于大多数应用程序中的Activity数量比继承TextView的TextView或小部件要少得多。随着复杂性的增加,这种情况将呈指数增长,因此该解决方案需要更少的代码更改。

感谢Ray Kuhnell


26

使用基础活动配置,可以将应用程序的文本大小进行放大/缩小,使所有活动都继承基础活动。

标准比例为1.0,2.0会将字体大小加倍,0.50将使其减半。

public  void adjustFontScale( Configuration configuration,float scale) {

    configuration.fontScale = scale;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);

}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adjustFontScale( getResources().getConfiguration());
}

1
工作得非常好。不会缩放工具栏标题大小,因为它在主题的深层'dp'中定义。 - Ridcully
2
提供的代码没有考虑用户的缩放设置(在“设置/辅助功能/字体大小”中),但是这可以很容易地添加进去。 - Ridcully
2
谢谢,这个方法可行。为了考虑用户的缩放,我使用了以下代码:systemScale = Settings.System.getFloat(context.getContentResolver(), Settings.System.FONT_SCALE, 1f); configuration.fontScale = scale * systemScale; //其余代码 - Jerry Sha
1
实现该目标最简单的方法是这样...我已经实现了它,现在我是一个满意的开发者! - Salar Arabpour

5
可能的解决方案是你创建一个基类,它扩展了TextView,并使用这个文本视图类作为编辑文本。希望你在第一屏幕上询问尺寸。在任何情况下,您在基类中设置文本大小即可解决问题。
例如,您可以在包com.example中创建此类,类名为BaseTextView,然后在xml文件中,您将写<com.example.BaseTextView ... />代替<TextView .../> 希望这能帮到你。

@Meena Rengarajan,您能否再解释一下?因为您已经将其作为正确答案接受了。我也尝试了同样的方法,但是没有起作用。请给一些提示。 - Krishna Shrestha

0
创建一个函数并将旋转器大小值作为参数传递。
void setSize(int size){
...
setTextSize()
// on All of the layout texts and views on screen

}

在所有视图上调用setTextSize(),并在屏幕上布局文本。

查看文档这里


0

为了缩放所有组件(即整个应用程序)的字体大小,有一种非常好的方法已经通过多个设备进行了实现和测试。这个解决方案可以应用于以下情况:静态声明dp大小单位(默认为android sp),缩放到所需的字体大小等。

该解决方案类似于Usama Saeed US提供的答案,但将覆盖所有错误情况。

声明静态实用方法来缩放字体大小。

    //LocaleConfigurationUtil.class
    public static Context adjustFontSize(Context context){
        Configuration configuration = context.getResources().getConfiguration();
        // This will apply to all text like -> Your given text size * fontScale
        configuration.fontScale = 1.0f;

        return context.createConfigurationContext(configuration);
    }

在你的所有活动中,重写attachBaseContext并在onCreate中调用util方法。
   @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocaleConfigurationUtil.adjustFontSize(newBase));
    }

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocaleConfigurationUtil.adjustFontSize(this);
    }

如果您正在使用片段,则覆盖onAttach方法。
@Override
public void onAttach(Context context) {
super.onAttach(LocaleConfigurationUtil.adjustFontSize(context));
}

-1

我不确定这是否有帮助。但是有一种东西叫做“SSP” - 可扩展文本尺寸单位。 将其添加到您的构建 gradle 中

implementation 'com.intuit.ssp:ssp-android:1.0.6'

并且这样使用

android:textSize="@dimen/_22ssp"

https://github.com/intuit/ssp


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