App內切換語言,app切換語言

來源:互聯網
上載者:User

App內切換語言,app切換語言

轉載請註明出處 http://www.cnblogs.com/cnwutianhao/p/6746981.html 

 

前幾天客戶提需求,對App增加一個功能,這個功能目前市面上已經很常見,那就是應用內切換語言。啥意思,就是 英、中、法、德、日。。。語言隨意切換。

(本案例採用Data-Bingding模式,麻麻再也不用擔心我findViewBy不到Id了哈哈,開個玩笑)

先上樣本圖:

 

代碼實現:

布局檔案(Data-Binding模式),很簡單就是兩行文字

<?xml version="1.0" encoding="utf-8"?><layout xmlns:android="http://schemas.android.com/apk/res/android">    <RelativeLayout xmlns:tools="http://schemas.android.com/tools"        android:layout_width="match_parent"        android:layout_height="match_parent"        tools:context="com.tnnowu.android.switchlanguage.MainActivity">        <TextView            android:id="@+id/titleTextView"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:text="@string/title"            android:textSize="30sp"            android:textStyle="bold" />        <TextView            android:id="@+id/descTextView"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@+id/titleTextView"            android:layout_centerHorizontal="true"            android:layout_marginTop="10dp"            android:text="@string/desc"            android:textSize="20sp" />    </RelativeLayout></layout>

 

從執行個體中我們可以看到右上方是有Menu

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    tools:context=".MainActivity">    <item        android:id="@+id/language_english"        android:orderInCategory="100"        android:title="@string/menu_english" />    <item        android:id="@+id/language_simplified_chinese"        android:orderInCategory="100"        android:title="@string/menu_simplified_chinese" />    <item        android:id="@+id/language_turkish"        android:orderInCategory="100"        android:title="@string/menu_turkish" />    <item        android:id="@+id/language_japanese"        android:orderInCategory="100"        android:title="@string/menu_japanese" /></menu>

(既然是多語言,所以就要有N個strings)

,本案例我建立了4種語言。

 

好的,Menu的布局寫完了,接下來就是實現Menu功能,記住實現Menu就兩套代碼,一個 onCreateOptionsMenu , 另一個是 onOptionsItemSelected 。

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    getMenuInflater().inflate(R.menu.menu, menu);    return true;}
@Overridepublic boolean onOptionsItemSelected(MenuItem item) {    int id = item.getItemId();    if (id == R.id.language_english) {        updateViews("en");    } else if (id == R.id.language_simplified_chinese) {        updateViews("zh");    } else if (id == R.id.language_turkish) {        updateViews("tr");    } else if (id == R.id.language_japanese) {        updateViews("ja");    }    return super.onOptionsItemSelected(item);}

 

在這裡,可以看到,我們自訂一個 updateViews() 方法,用來實現切換預言時介面的改變

private void updateViews(String languageCode) {    Context context = LocaleHelper.setLocale(this, languageCode);    Resources resources = context.getResources();    mBinding.titleTextView.setText(resources.getString(R.string.title));    mBinding.descTextView.setText(resources.getString(R.string.desc));    setTitle(resources.getString(R.string.toolbar_title));}

 

公布一個 語言判斷的類 LocaleHelper

public class LocaleHelper {    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";    public static Context onAttach(Context context) {        String lang = getPersistedData(context, Locale.getDefault().getLanguage());        return setLocale(context, lang);    }    public static Context onAttach(Context context, String defaultLanguage) {        String lang = getPersistedData(context, defaultLanguage);        return setLocale(context, lang);    }    public static String getLanguage(Context context) {        return getPersistedData(context, Locale.getDefault().getLanguage());    }    public static Context setLocale(Context context, String language) {        persist(context, language);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {            return updateResources(context, language);        }        return updateResourcesLegacy(context, language);    }    private static String getPersistedData(Context context, String defaultLanguage) {        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);    }    private static void persist(Context context, String language) {        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);        SharedPreferences.Editor editor = preferences.edit();        editor.putString(SELECTED_LANGUAGE, language);        editor.apply();    }    @TargetApi(Build.VERSION_CODES.N)    private static Context updateResources(Context context, String language) {        Locale locale = new Locale(language);        Locale.setDefault(locale);        Configuration configuration = context.getResources().getConfiguration();        configuration.setLocale(locale);        return context.createConfigurationContext(configuration);    }    @SuppressWarnings("deprecation")    private static Context updateResourcesLegacy(Context context, String language) {        Locale locale = new Locale(language);        Locale.setDefault(locale);        Resources resources = context.getResources();        Configuration configuration = resources.getConfiguration();        configuration.locale = locale;        resources.updateConfiguration(configuration, resources.getDisplayMetrics());        return context;    }}

 

最後還要做的操作就是,自訂一個Application類,用來設定App的預設語言(當然了,要將這個Application應用到Manifest中)

public class BaseApplication extends Application {    @Override    protected void attachBaseContext(Context base) {        super.attachBaseContext(LocaleHelper.onAttach(base, "en"));    }}

 

本案例實現App內語言切換代碼量不大,通俗易懂,無垃圾代碼。

範例程式碼:App內切換語言

 

關注我的新浪微博,請認準黃V認證,擷取最新安卓開發資訊。

關注科技評論家,領略科技、創新、教育以及最大化人類智慧與想象力!

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.