###### tags: `Android` `Java` # 多國語系 多國語系只要在value中 建立一個不同國家語言的string,並進行語言對照就可以使用 App會自動抓取裝置的系統語言進行string的選擇 若專案中沒有該系統語言的string列表時,默認會抓取沒有國籍的string 即string.xml後方沒有語言和國家的簡稱 因為英文是國際語言,所以默認的string大家都會設定成英文 避免語言有無法適配時,至少文字為英文 以上可以參考此文章完成 > http://fishtsaii91.blogspot.com/2018/03/android-studio-android-app-app.html ## 圖片多國語系 除了string之外,其實大部分的res內部資料都可以進行多國語言切換 我們試著切換圖片,如同string,我們也要建立一個不同語言的drawable資料夾 目前在Android Studio中好像沒看到可以輕鬆建立的方式,所以我們土法煉鋼 在檔案總管建立資料夾,原本的是各種尺寸的drawable,例如: drawable-hdpi 我們新建 drawable-zh-rTW-hdpi,並在裡面放入不同圖片,這樣就完成囉! ## 進階版-動態切換 上述方法是根據手機裝置的語言切換,但有時候使用者可能單純只想更換App的語言時 我們就要進行內部切換,也就是讓使用者自己進行動態的語言選擇 1. 使用sharedPreferences儲存使用者選擇的語言 (儲存完後需要重新啟動Activity) 2. 覆寫Activity的attachBaseContext(Context context) 3. 讀取sharedPreferences進行語言設定 attachBaseContext ```java= // Set application language @Override protected void attachBaseContext(Context newBase) { Configuration config = newBase.getResources().getConfiguration(); String language = new UserInfoSharedPreferences(newBase).readLanguage(); if (language.equals("zh") || language.isEmpty()) config.setLocale(Locale.TRADITIONAL_CHINESE); else config.setLocale(Locale.ENGLISH); super.attachBaseContext(newBase.createConfigurationContext(config)); } ``` app 重啟 ```java= Intent i = new Intent(getBaseContext(), JumpView.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); finish(); ``` ## 單數複數處理 遇到單數複數就會很頭痛,但 Android 其實有處理方式,就是使用 Quantity strings (plurals) https://developer.android.com/guide/topics/resources/string-resource#Plurals https://blog.csdn.net/teagreen_red/article/details/78269950 ## 養成好習慣Style 1. 用途相似的放在一起並備註,id name的前缀可以統一 2. 只有一種語言但特殊用途的文字放在默認string (ex: 網址 3. 只有某處使用的語言獨立出來,例如特定元件、actionbar的標題 (避免有相似的會衝突 4. 關鍵字獨立出來,例如id name不可為public,可改成_public 5. 單字、句子、額外文字(ex: %s)、額外數字(ex: %d) 分開 ## 採坑紀錄 ### 線上版不能切換 實際問題是 bundle apk 它分割了 Locale 文件,在 bundle apk 默認情況下會分裂 要避免這個情況,可以在 build.gradle 文件的 android塊中,可以聲明將生成哪些拆分 ``` bundle { language { // Specifies that the app bundle should not support // configuration APKs for language resources. These // resources are instead packaged with each base and // dynamic feature APK. enableSplit = false } } ``` https://stackoverflow.com/questions/55265834/change-locale-not-work-after-migrate-to-androidx ### 打印 % %d 是用來保留數字,但想要單純打印 %,要用 \%% ```xml= <string name="zone_50">Fat Burning (50\%% to 60\%%)</string> ``` https://stackoverflow.com/questions/4414389/android-xml-percent-symbol
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up