Android强制为自身应用设置实现多语言

推荐安卓开发神器(里面有各种UI特效和android代码库实例)

每一个Activity中都要加: android:configChanges="locale"。

加 <supports-screens>是为了解决如下问题:

中文资源:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">你好,这是测试文字!</string>
<string name="app_name">LanguageTest</string>
<string name="btn_name">Change to English</string>
</resources>
英文资源:

<?xml version="1.0" encoding="utf-8"?>

<resources>
<string name="hello">Hello World, MainActivity!</string>
<string name="app_name">LanguageTest</string>
<string name="btn_name">变成中文</string>
</resources>
package com.hkp;

import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
/** Called when the activity is first created. */

public String [] langes = {"zh","en"};
public static int count = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView tv = (TextView) findViewById(R.id.hello1);
String str = this.getResources().getString(R.string.hello);
tv.setText(str);
Button btn = (Button)findViewById(R.id.btn_change);
btn.setText(R.string.btn_name);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String languageToLoad = langes[count++%2];
setLanguage(languageToLoad);
//刷新界面
Intent intent = new Intent();

intent.setClass(MainActivity.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
MainActivity.this.startActivity(intent);
}
});
}

/**
* Set the Language of Application
*
* @param lang
* the language to set
*/
private void setLanguage(String lang) {
String languageToLoad = lang;
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, null);
}
}

AndroidManifest.xml中:

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".MainActivity"

android:label="@string/app_name"

android:configChanges="locale">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>



</application>

<supports-screens

android:smallScreens="true"

android:normalScreens="true"

android:largeScreens="true"

android:anyDensity="true"/>



你可能感兴趣的:(android)