切换系统语言

88 篇文章 1 订阅
74 篇文章 1 订阅

一般这种需要在自己的APP里去切换系统语言的需求是比较少的,毕竟系统设置里有了,但是万一项目中碰到这种需求,可以按照如下代码去切换,本人亲测有效


public void setLan(Locale locale) {
		//

		Class amnClass = null;
		try {
			amnClass = Class.forName("android.app.ActivityManagerNative");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Object amn = null;
		Configuration config = null;

		// amn = ActivityManagerNative.getDefault();
		Method methodGetDefault = null;
		try {
			methodGetDefault = amnClass.getMethod("getDefault");
		
		methodGetDefault.setAccessible(true);
		
			amn = methodGetDefault.invoke(amnClass);
		Method methodGetConfiguration = null;
		
			methodGetConfiguration = amnClass.getMethod("getConfiguration");
		
		methodGetConfiguration.setAccessible(true);
		
			config = (Configuration) methodGetConfiguration.invoke(amn);
		}catch (Exception e1) {
			
			e1.printStackTrace();
		}
		// config.userSetLocale = true;
		Class configClass = config.getClass();
		Field f = null;
		
		try {
			f = configClass.getField("userSetLocale");
			f.setBoolean(config, true);
		}  catch (Exception e) {
		
			e.printStackTrace();
			
		}
		
		Log.d("wzh", "mCurrentLanguage" + mCurrentLanguage);
		// set the locale to the new value
		config.locale = locale;

		// amn.updateConfiguration(config);
		Method methodUpdateConfiguration = null;
		try {
			methodUpdateConfiguration = amnClass.getMethod(
					"updateConfiguration", Configuration.class);
		
		methodUpdateConfiguration.setAccessible(true);
		
			methodUpdateConfiguration.invoke(amn, config);
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

以上代码就是一个方法而已,需要切换成什么语言就传什么参数,例如:要切换成中文就调用setLan(Locale.SIMPLIFIED_CHINESE)即可,要切换成英文就调用setLan(Locale.ENGLISH)即可

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java项目中切换系统语言,可以通过以下步骤来实现: 1. 创建语言资源文件:根据需要切换语言,创建对应的语言资源文件。例如,如果需要支持英文和中文两种语言,可以创建两个资源文件:`en_US.properties`(英文)和`zh_CN.properties`(中文)。资源文件中使用键值对的形式来存储对应语言的文本。 2. 加载语言资源文件:在Java项目中,可以使用`ResourceBundle`类来加载语言资源文件。通过调用`ResourceBundle.getBundle()`方法,并传入资源文件的名称和当前的`Locale`对象,即可加载对应的资源文件。`Locale`对象用于指定当前的语言环境。 3. 设置语言环境:通过调用`Locale.setDefault()`方法,将当前的语言环境设置为需要切换语言。可以通过创建一个`Locale`对象,设置对应的语言代码(例如:"en"表示英文,"zh"表示中文)和国家代码(例如:"US"表示美国,"CN"表示中国)来构建`Locale`对象。 4. 获取语言资源文本:通过调用`ResourceBundle.getString()`方法,传入对应的键值,即可获取当前语言环境下的文本内容。这样就可以根据需要在界面上显示对应的语言文本了。 通过以上步骤,就可以在Java项目中实现切换系统语言的功能。可以根据具体需求,使用语言资源文件来存储不同语言的文本内容,并通过`ResourceBundle`和`Locale`类来加载和切换语言环境,实现多语言支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值