天天看點

android語言切換

不使用生命周期切換語言

1:檔案結構

android語言切換

在xml中将對應的value建立xml檔案 裡邊的内容和對應的string内容一樣

2:将要進行語言切換的畫面控件全部提到Activity中 在activity中定義一個方法進行重新整理這些控件

private void refreshUI() {
        moretitle.setText(Strings.getString(R.string.app_name));
        updateversion_text.setText(Strings.getString(R.string.versionupdate));
        share_text.setText(Strings.getString(R.string.sharetofriend));
        aboutus_text.setText(Strings.getString(R.string.aboutus));
        guesttel_text.setText(Strings.getString(R.string.guesttel));
        switchlangure_text.setText(Strings.getString(R.string.switchlangure));
    }
           

3:Strings.java是用來解析xml的

package com.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;

import com.aichuxing.activity.R;

/**
 */
public class Strings {
	public static final String LANGUAGE_JAPANESE = "japanese";
	public static final String LANGUAGE_CHINESE = "chinese";
	/** 一個Integer對應一個string或者string[],即<Integer, Object>。 */
	public static HashMap<Integer, Object> stringCustom;
	/** 辨別目前顯示的語系;預設值為英文。 */
	public static String language = LANGUAGE_CHINESE;
	/** 預設*/
	private int xmlid = R.xml.chinese;

	public static String getLanguage() {
		return language;
	}

	public void initLanguage(Context context) {
		stringCustom = readStringsXML(context, xmlid);
	}

	/** 擷取指定id的字元串。 */
	public static String getString(int strId) {
		return (String) stringCustom.get(strId);
	}

	/** 擷取指定id的字元串數組。 */
	public static String[] getStringArray(int strArrId) {
		return (String[]) stringCustom.get(strArrId);
	}

	private static String[] readStringArray(XmlResourceParser xmlParser)
			throws XmlPullParserException, IOException {
		String[] arr = null;
		LinkedList<String> list = new LinkedList<String>();
		String tagName, tagValue;
		while (true) {
			xmlParser.next();
			tagName = xmlParser.getName();
			if ("string-array".equals(tagName)) {
				arr = new String[list.size()];
				// 這個函數設計得好奇怪,傳參和返參都一樣。
				// list.toArray(arr);作用同下:
				arr = list.toArray(arr);
				break;
			}
			tagName = xmlParser.getName();
			if ((xmlParser.getEventType() == XmlResourceParser.START_TAG) && tagName.equals("item")) {
				xmlParser.next();
				tagValue = xmlParser.getText();
				list.add(tagValue);
				// Log.d("ANDROID_LAB", tagName + "=" + tagValue);
			}
		}
		return arr;
	}

	private static HashMap<Integer, Object> readStringsXML(Context context, int xmlId) {
		HashMap<Integer, Object> hashMap = new HashMap<Integer, Object>();
		Resources res = context.getResources();
		String pkg = context.getPackageName();
		XmlResourceParser xmlParser = context.getResources().getXml(xmlId);
		try {
			String tagName, attName, attValue, tagValue;
			int identifier = -1;
			int eventType = xmlParser.next();
			while (eventType != XmlResourceParser.END_DOCUMENT) {
				if (eventType == XmlResourceParser.START_DOCUMENT) {
					// Log.d("ANDROID_LAB", "[Start document]");
				} else if (eventType == XmlResourceParser.END_DOCUMENT) {
					// Log.d("ANDROID_LAB", "[End document]");
				} else if (eventType == XmlResourceParser.START_TAG) {
					tagName = xmlParser.getName();
					if ("string".equals(tagName)) {
						attName = xmlParser.getAttributeName(0);
						attValue = xmlParser.getAttributeValue(0);
						eventType = xmlParser.next();
						if (eventType == XmlResourceParser.TEXT) {
							tagValue = xmlParser.getText();
							identifier = res.getIdentifier(attValue, "string", pkg);
							hashMap.put(identifier, tagValue);
						}
					} else if ("string-array".equals(tagName)) {
						attName = xmlParser.getAttributeName(0);
						attValue = xmlParser.getAttributeValue(0);
						identifier = res.getIdentifier(attValue, "array", pkg);
						String[] arr = readStringArray(xmlParser);
						hashMap.put(identifier, arr);
					}
				} else if (eventType == XmlResourceParser.END_TAG) {
				} else if (eventType == XmlResourceParser.TEXT) {
				}
				eventType = xmlParser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hashMap;
	}

	/**
	 * 設定新的語系。<br/>
	 * 根據新設定值對stringCustom進行更新。<br/>
	 * 
	 * @param context
	 *            調用者。
	 * @param language
	 *            語系名稱。
	 * 
	 * @see LANGUAGE_JAPANESE
	 * @see LANGUAGE_CHINESE
	 * */
	public void setLanguage(Context context, String language) {
		if (language.equals(Strings.language)) {
			return;
		}
		if (language.equals(Strings.LANGUAGE_CHINESE)) {
		    
			stringCustom = readStringsXML(context, R.xml.chinese);
			xmlid = R.xml.chinese;
			Strings.language = language;
		} else if (language.equals(Strings.LANGUAGE_JAPANESE)) {
			stringCustom = readStringsXML(context, R.xml.japanese);
			xmlid = R.xml.japanese;
			Strings.language = language;
		} else {
			if (Strings.language.equals(Strings.LANGUAGE_JAPANESE) == false) {
				stringCustom = readStringsXML(context, R.xml.chinese);
				xmlid = R.xml.japanese;
				Strings.language = Strings.LANGUAGE_CHINESE;
			}
		}
	}
}
           

4:切換語言的事件

AiChuXingApplication.config.locale = Locale.JAPANESE;
                        AiChuXingApplication.resources.updateConfiguration(
                                AiChuXingApplication.config,
                                AiChuXingApplication.dm);
           
//上邊兩行是講應用中的還沒有oncreate的activity應用切換後的語言
                        AiChuXingApplication.STRINGS.setLanguage(
                                SwitchLangure.this, Strings.LANGUAGE_JAPANESE);
                        Intent mIntent = new Intent(ACTION_NAME);
                        mIntent.putExtra("LANGURE", Strings.LANGUAGE_JAPANESE);
                        // 發送廣播
                        sendBroadcast(mIntent);
                        SwitchLangure.this.finish();
           

5:Application中

STRINGS = new Strings();
        resources = getResources();
        config = resources.getConfiguration();
        dm = resources.getDisplayMetrics();
           

6:在已經oncreate并且沒有ondestory的activity定義一個廣播用來接收切換語言的廣播

public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME);
        // 注冊廣播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            AiChuXingApplication.STRINGS.setLanguage(MoreActivity.this, intent.getExtras().getString("LANGURE"));
            if (action.equals(ACTION_NAME)) {
                refreshUI();
            }
        }

    };
           

7:當然在使用之前要進行注冊廣播

AiChuXingApplication.STRINGS.initLanguage(this);//初始化
        registerBoradcastReceiver();//注冊廣播
        refreshUI();
           

切換完成