Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android动态设置app当前运行语言的方法大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

android开发中有时候碰到切换语言的需求,这时候需要通过代码动态改变当前运行语言。

package com.example.androidtest;

import java.util.Locale;

import android.os.bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.resources;
import android.util.Displaymetrics;
import android.view.Menu;
import android.view.View;
import android.widget.button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceStatE) {
		super.onCreate(savedInstanceStatE);
		setContentView(R.layout.activity_main);

		Button btnLang = (Button) findViewById(R.id.btn);
		// 按下按钮改变语言类型,在“简体中文”和“英文”之间切换
		btnLang.setOnClickListener(new View.onClickListener() {
			
			@Override
			public void onClick(View v) {
				// 获取当前Locale(包含语言信息)
				Locale curLocale = getresources().getConfiguration().locale;
				
				// 判断语言类型,有以下两种判断方式
				
				// 方法一,通过Locale的equals方法
				// public Boolean equals (Object object) 
				//   Returns true if object is a locale with the same language,country and variant. 
				if (curLocale.equals(Locale.SIMPLIFIED_CHInesE)) {
					setLang(Locale.ENGLISH);
				} else {
					setLang(Locale.SIMPLIFIED_CHInesE);
				}
				
				// 方法二,通过语言码,getLanguage()方法可以获得对应语言码
				// public String getLanguage () 
				// 	Returns the language code for this Locale or the empty String if no language was set. 
//				if (curLocale.getLanguage().equals(Locale.SIMPLIFIED_CHInesE.getLanguage())) {
//					setLang(Locale.ENGLISH);
//				} else {
//					setLang(Locale.SIMPLIFIED_CHInesE);
//				}
			}
		});
	}

	private void setLang(Locale l) {
		// 获得res资源对象
		resources resources = getresources();
		// 获得设置对象
		Configuration config = resources.getConfiguration();
		// 获得屏幕参数:主要是分辨率,像素等。
		Displaymetrics dm = resources.getDisplaymetrics();
		// 语言
		config.locale = l;
		resources.updateConfiguration(config,dm);
		
		// 刷新activity才能马上奏效
		startActivity(new Intent().setClass(MainActivity.this,MainActivity.class));
		MainActivity.this.finish();
	}

	@Override
	public Boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main,menu);
		return true;
	}

}

通过下面一行代码获得当前语言信息

Locale curLocale = getresources().getConfiguration().locale;

判断语言和设置语言部分有详细注释,就不做过多解释啦!

资源文件需要支持多语言环境,这样才能看到切换语言的@L_944_19@!

android动态设置app当前运行语言的方法

 

创建values-en文件夹,并创建英文版Strings.xml文件。 

以上这篇android动态设置app当前运行语言的方法就是小编分享给大家的全部内容了,希望能给大家一个,也希望大家多多支持编程小技巧。

大佬总结

以上是大佬教程为你收集整理的android动态设置app当前运行语言的方法全部内容,希望文章能够帮你解决android动态设置app当前运行语言的方法所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:androidapp