androidmauimaui-android

.NET MAUI Per-app language preference on Android


In Android, a newer feature is allowing users to change language on a per-app basis .

Is there any way to do this in .NET MAUI? The AndroidManifest.xml is editable, but I don't think build.gradle is. If the build.gradle file isn't possible to edit, then I guess it isn't possible.

The only close things I've found is https://github.com/xamarin/xamarin-android/commit/b423ff68a6d11230bb493c3cb0633ff2a9c37b20.


Solution

  • There is no need to change any Gradle files to make Per-app language preferences work.

    Just follow this steps and it will work for you:

    1. Add Platforms/Android/Resources/xml/locales_config.xml with languages for App settings (Build action should be "AndroidResource"):
    <?xml version="1.0" encoding="utf-8"?>
    <locale-config xmlns:android="http://schemas.android.com/apk/res/android">
        <locale android:name="en-US"/>
        <locale android:name="en-GB"/>
        <locale android:name="fr"/>
    </locale-config>
    
    1. Edit AndroidManifest.xml, by adding a line to point to locales_config:
    <manifest>
        ...
        <application
            ...
            android:localeConfig="@xml/locales_config">
        </application>
    </manifest>
    
    1. Add Resources.resx files (I prefer to add them to Resources/Strings/AppResources.resx)

    2. Use your AppResources.resx in any view:

    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:strings="clr-namespace:PerAppLanguagePreference.Resources.Strings"
                 x:Class="PerAppLanguagePreference.MainPage">
                 ...
                 <Label
                    Text="{Static strings:AppResources.HelloWorld}"
                    SemanticProperties.HeadingLevel="Level1"
                    FontSize="32"
                    HorizontalOptions="Center" />
                 ...
    </ContentPage>
    

    After app language change in Settings, according AppResources.xx.resx will be used.