You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI中实现Android应用级语言偏好设置?

在.NET MAUI中实现Android应用级语言切换

可以实现Android应用级语言切换功能,不需要修改build.gradle,通过配置AndroidManifest.xml和编写平台特定逻辑即可完成,以下是具体步骤:

1. 配置AndroidManifest与语言列表

首先在Android项目的AndroidManifest.xml中,给<application>标签添加locale配置声明:

<application ... android:localeConfig="@xml/locales_config">

接着在Android项目的Resources/xml目录下创建locales_config.xml文件,定义应用支持的语言列表:

<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
    <locale android:name="zh-CN"/>
    <locale android:name="en-US"/>
    <!-- 添加其他需要支持的语言代码 -->
</locale-config>

2. 准备多语言资源文件

在.NET MAUI共享项目中创建多语言资源文件:

  • 默认资源:Resources/Strings.resx
  • 中文资源:Resources/Strings.zh-CN.resx
  • 英文资源:Resources/Strings.en-US.resx

在这些文件中添加对应语言的键值对,用于界面文本的多语言展示。

3. 实现平台级语言切换逻辑

因为Android应用级语言切换需要调用原生API,所以在Android项目中编写语言切换服务:

首先在共享项目定义接口:

public interface ILanguageService
{
    void SetLanguage(string languageCode);
}

然后在Android项目中实现该接口:

using Android.App;
using Android.Content.Res;
using Android.OS;
using Microsoft.Maui.Controls;

[assembly: Dependency(typeof(AndroidLanguageService))]
namespace YourAppNamespace.Platforms.Android
{
    public class AndroidLanguageService : ILanguageService
    {
        public void SetLanguage(string languageCode)
        {
            var currentActivity = Platform.CurrentActivity;
            if (currentActivity == null) return;

            var targetLocale = new Java.Util.Locale(languageCode);
            Java.Util.Locale.Default = targetLocale;

            var config = new Configuration(currentActivity.Resources.Configuration);
            if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
            {
                config.SetLocale(targetLocale);
                config.SetLayoutDirection(targetLocale);
                currentActivity.CreateConfigurationContext(config);
            }
            else
            {
                config.Locale = targetLocale;
                currentActivity.Resources.UpdateConfiguration(config, currentActivity.Resources.DisplayMetrics);
            }

            // 重启主Activity使语言设置生效
            var launchIntent = currentActivity.PackageManager.GetLaunchIntentForPackage(currentActivity.PackageName);
            launchIntent.AddFlags(ActivityFlags.ClearTop);
            currentActivity.StartActivity(launchIntent);
            currentActivity.Finish();
        }
    }
}

最后在共享项目中通过依赖服务调用切换逻辑:

var languageService = DependencyService.Get<ILanguageService>();
languageService?.SetLanguage("zh-CN"); // 切换到中文

关于build.gradle的疑问

你提到的Xamarin.Android提交已经被整合到.NET MAUI的Android平台实现中,不需要手动修改build.gradle文件,.NET MAUI会自动处理相关的配置和依赖,不影响功能实现。

内容的提问来源于stack exchange,提问作者HubbleCommander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 01:51:21