Android中实现多语言的切换

本文深入分析了Android应用中多语言切换的常见问题和优化策略,通过对比三种方法,揭示了错误理解可能导致的问题,并提出了更为有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上流行几种多语言的切换,但可能是作者对Android的理解有所偏差,所以某些地方上存在者一点错误,走了弯路。

在开始之前,大家不妨先看一下不是太好的3种方法吧(这里只是探讨更好的方法,为精简本文篇幅,故引用原博客,本人对原博客作者并无不敬之处,相反,对于原作者的贡献精神以及早期资料搜集的引导非常尊重)。

##########################################################################################

1、代码以及效果图

package com.example.newthingstest;

import java.util.Locale;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityLanguage extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		final TextView tv = new TextView(this) ;
		tv.setText(R.string.lang_test);
		tv.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				setResoucesLocale(Locale.CHINESE) ;
				tv.setText(R.string.lang_test);
			}
		}, 3000) ;
		tv.setTextColor(0xFFFF0000);
		tv.setBackgroundResource(android.R.color.black);
		setContentView(tv) ;
	}
	
	protected void setResoucesLocale(Locale loc) {
		Configuration config = this.getResources().getConfiguration() ;
		config.locale = loc ;
		this.getResources().updateConfiguration(config, this.getResources().getDisplayMetrics());
	}
	
}

本人使用的是模拟器测试的,默认语言是English。

效果如下




2、代码分析

		Configuration config = this.getResources().getConfiguration() ;
		config.locale = loc ;
		this.getResources().updateConfiguration(config, this.getResources().getDisplayMetrics());

首先获取当前系统中的Configuration,并修改其中的locale属性,然后调用updateConfiguration(),注意,这是关键,这里之前的开发者误以为是更新UI,其实这里这是更新ID对资源的引用,如之前指向的是values-en文件夹内的string.xml,修改后指向values-zh内的string.xml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值