Changing the locale is modifying the text dimensions of my app

放肆的年华 提交于 2020-01-05 12:29:08

问题


I'm trying to change the language on my Android app and I'm using this code:

String languageToLoad  = "en";
Locale locale = new Locale(languageToLoad); 
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, 
getBaseContext().getResources().getDisplayMetrics());

I've created different values directories (\values-fr, \values-it, etc.) where I put my string.xml files.

Changing the language works normally, but the problem is that it's changing text dimensions in my app (text sizes on textviews, menu, dialogs, edittexts, buttons...basically in all my app).

Removing the block code that changes the locale, the app layout gets back to normal. Is the getDisplayMetrics() creating the problem?

I'm using styles for some of the texts:

<style name="title_font">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#095080</item>
        <item name="android:textSize">26sp</item>
        <item name="android:textStyle">bold</item>
</style> 

And some example of textviews:

<TextView
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        style="@style/title_font"
        android:text="@string/login_title" />

<TextView
      android:id="@+id/label_user"
      android:textStyle="bold"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_marginTop="50dp"
      android:textAppearance="?android:attr/textAppearanceMedium" 
      android:text="@string/user_label"
      android:layout_below="@+id/login"/>

Can you tell me why is this happening and how to solve it? If you need any additional information, please ask.


回答1:


After a few hours of searching, I found the solution in a comment here: Android changing language configuration messes up layout

Basically you have to replace

Configuration config = new Configuration();

with

Configuration config = getBaseContext().getResources().getConfiguration();

This way, you don't create a new configuration, but only modifying the existing one.



来源:https://stackoverflow.com/questions/24906971/changing-the-locale-is-modifying-the-text-dimensions-of-my-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!