前言
前段時間接到一個需求,要動態的增加多語言語種,且可以動態更新用戶app上的不規范語言(比如一個英語過長導致按鈕內顯示不全)
服務端的邏輯和前段動態獲取的邏輯就不說了
修改app內的語言參考這篇安卓多語言設定,深淵巨坑,適配7.0以上,并且解決因WebView產生的問題
正文
首先確定一下安卓中有幾種獲取字串的方式
1.Context#getResources().getString()
2.Context#getString()//其實內部還是用的上一種方式,只不過少寫了一點代碼
3.xml#android:text="@string/xxx"
那其實算下來只有兩種,一種是通過resources來獲取String,另一種是在xml決議的時候獲取String
第一種:通過包裝并攔截resources來Hook getString()
原理其實也很簡單:
通過觀察原始碼,發現Context每次呼叫getString()之前都會先呼叫一下getResources(),這時只要重寫一下Application和BaseActivity的getResources(),回傳自己包裝的resources,即可攔截到getString()方法,然后通過資源id獲取資源名,查找服務器回傳的對應key的value,如果有就回傳服務器的,沒有則使用應用自身的.
至于為什么不需要重寫BaseFragment和BaseDialog的,因為BaseFragment的getResources()會呼叫requireContext(),而requireContext()回傳的Context物件就是附加到的Activity物件,所以不用設定,同理Dialog需要在構造的時候傳入Activity,so
ps:既然Fragment是每次呼叫getString()都會呼叫getContext(),那這樣在Fragment銷毀之后就不能呼叫getString()了,否則就會拋例外!
代碼如下:
BaseActivity為例:
private var resources: Resources? = null
override fun getResources(): Resources {
if (resources == null) {
resources = LanguageResources(super.getResources())
}
return resources!!
}
資源包裝類LanguageResources如下:
/**
* creator: lt lt.dygzs@qq.com
* 通過攔截appResources來攔截字串
*/
class LanguageResources(val resources: Resources)
: Resources(resources.assets, resources.displayMetrics, resources.configuration) {
val myBidiFormatter: BidiFormatter = BidiFormatter.getInstance()
override fun getText(id: Int): CharSequence {
resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it } }
return resources.getText(id)
}
override fun getText(id: Int, def: CharSequence?): CharSequence? {
resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it } }
return resources.getText(id, def)
}
override fun getString(id: Int): String {
resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it } }
return resources.getString(id)
}
override fun getString(id: Int, vararg formatArgs: Any?): String {
resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it.format(*formatArgs) } }
return resources.getString(id, *formatArgs)
}
override fun getTextArray(id: Int): Array<CharSequence?> {
//專案內不要使用array
return resources.getTextArray(id)
}
override fun getStringArray(id: Int): Array<String?> {
//專案內不要使用array
return resources.getStringArray(id)
}
override fun getQuantityText(id: Int, quantity: Int): CharSequence {
return resources.getQuantityText(id, quantity)
}
override fun getQuantityString(id: Int, quantity: Int, vararg formatArgs: Any?): String {
return resources.getQuantityString(id, quantity, *formatArgs)
}
override fun getQuantityString(id: Int, quantity: Int): String {
return resources.getQuantityString(id, quantity)
}
override fun getIntArray(id: Int): IntArray {
return resources.getIntArray(id)
}
override fun obtainTypedArray(id: Int): TypedArray {
return resources.obtainTypedArray(id)
}
override fun getDimension(id: Int): Float {
return resources.getDimension(id)
}
override fun getDimensionPixelOffset(id: Int): Int {
return resources.getDimensionPixelOffset(id)
}
override fun getDimensionPixelSize(id: Int): Int {
return resources.getDimensionPixelSize(id)
}
override fun getFraction(id: Int, base: Int, pbase: Int): Float {
return resources.getFraction(id, base, pbase)
}
override fun getDrawable(id: Int): Drawable? {
return resources.getDrawable(id)
}
@RequiresApi(21)
override fun getDrawable(id: Int, theme: Theme?): Drawable? {
return resources.getDrawable(id, theme)
}
override fun getDrawableForDensity(id: Int, density: Int): Drawable? {
return resources.getDrawableForDensity(id, density)
}
@RequiresApi(21)
override fun getDrawableForDensity(id: Int, density: Int, theme: Theme?): Drawable? {
return resources.getDrawableForDensity(id, density, theme)
}
override fun getMovie(id: Int): Movie? {
return resources.getMovie(id)
}
override fun getColor(id: Int): Int {
return resources.getColor(id)
}
override fun getColorStateList(id: Int): ColorStateList {
return resources.getColorStateList(id)
}
override fun getBoolean(id: Int): Boolean {
return resources.getBoolean(id)
}
override fun getInteger(id: Int): Int {
return resources.getInteger(id)
}
override fun getLayout(id: Int): XmlResourceParser {
return resources.getLayout(id)
}
override fun getAnimation(id: Int): XmlResourceParser {
return resources.getAnimation(id)
}
override fun getXml(id: Int): XmlResourceParser {
return resources.getXml(id)
}
override fun openRawResource(id: Int): InputStream {
return resources.openRawResource(id)
}
override fun openRawResource(id: Int, value: TypedValue?): InputStream {
return resources.openRawResource(id, value)
}
override fun openRawResourceFd(id: Int): AssetFileDescriptor? {
return resources.openRawResourceFd(id)
}
override fun getValue(id: Int, outValue: TypedValue?, resolveRefs: Boolean) {
resources.getValue(id, outValue, resolveRefs)
}
override fun getValueForDensity(id: Int, density: Int, outValue: TypedValue?, resolveRefs: Boolean) {
resources.getValueForDensity(id, density, outValue, resolveRefs)
}
override fun getValue(name: String?, outValue: TypedValue?, resolveRefs: Boolean) {
resources.getValue(name, outValue, resolveRefs)
}
override fun obtainAttributes(set: AttributeSet?, attrs: IntArray?): TypedArray? {
return resources.obtainAttributes(set, attrs)
}
override fun updateConfiguration(config: Configuration?, metrics: DisplayMetrics?) {
if (resources == null)
super.updateConfiguration(config, metrics)
else
resources.updateConfiguration(config, metrics)
}
override fun getDisplayMetrics(): DisplayMetrics? {
return resources.displayMetrics
}
override fun getConfiguration(): Configuration? {
return resources.configuration
}
override fun getIdentifier(name: String?, defType: String?, defPackage: String?): Int {
return resources.getIdentifier(name, defType, defPackage)
}
override fun getResourceName(resid: Int): String? {
return resources.getResourceName(resid)
}
override fun getResourcePackageName(resid: Int): String? {
return resources.getResourcePackageName(resid)
}
override fun getResourceTypeName(resid: Int): String? {
return resources.getResourceTypeName(resid)
}
override fun getResourceEntryName(resid: Int): String? {
return resources.getResourceEntryName(resid)
}
override fun parseBundleExtras(parser: XmlResourceParser?, outBundle: Bundle?) {
resources.parseBundleExtras(parser, outBundle)
}
override fun parseBundleExtra(tagName: String?, attrs: AttributeSet?, outBundle: Bundle?) {
resources.parseBundleExtra(tagName, attrs, outBundle)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun getColor(id: Int, theme: Theme?): Int {
return resources.getColor(id, theme)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun getColorStateList(id: Int, theme: Theme?): ColorStateList {
return resources.getColorStateList(id, theme)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun getFont(id: Int): Typeface {
return resources.getFont(id)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun getFloat(id: Int): Float {
return resources.getFloat(id)
}
}
簡單解釋一下:resources.getResourceEntryName()是通過id獲取對應的資源名,thisLanguageKVMap是從服務端獲取的多語言鍵值對HashMap(因為查找快),而我沒有攔截getStringArray()和getTextArray()是因為專案內只有一個地方用了,且多語言不好搞,且實作方式不同,我就給改成getString()的形式懶得去研究它了
ps:不能混淆資源名(騰訊的一個混淆資源框架),否則該方案無效
pps:順便吐槽一下,為啥kotlin的類委托只支持介面,不支持類..好坑,多寫了一堆模板代碼
第二種:通過攔截xml決議來Hook @string/
最開始我通過參考TextView的text獲取邏輯,然后找到TypedArray#getText(),然后發現傳進去的是個index,然后各種亂七八糟不熟悉的東西快給我繞暈了,果斷使用其他方案
然后我想起來前兩年有個很火的快捷開發的方案,通過攔截View生成來在xml中寫shape,當時我也模仿寫了個ShapeAndSelectUtil,用到的原理也是攔截LayoutInflater.Factory2,正好能用這個來攔截xml決議
原理:
通過攔截View的創建程序,拿到會用到@string/的View的物件(比如TextView和EditText或自定義View),獲取對應的id并重新從key value中獲取和設定
代碼如下:
//在BaseActivity的onCreate()中的super.onCreate()之前呼叫
layoutInflater.factory2 = LanguageLayoutInflaterFactory(this)
/**
* creator: lt lt.dygzs@qq.com
*/
class LanguageLayoutInflaterFactory(val activity: Activity) : LayoutInflater.Factory2 {
private val APP_KEY = "http://schemas.android.com/apk/res-auto"
private val ANDROID_KEY = "http://schemas.android.com/apk/res/android"
//sdk的activity使用的布局生成器
private val delegate: AppCompatDelegate by lazy(LazyThreadSafetyMode.NONE) { AppCompatDelegate.create(activity, null) }
//獲取默認的createView方法,可以在這里判斷并適配換膚框架等
fun checkAndCreateView(parent: View?, name: String?, context: Context, attrs: AttributeSet): View? {
return when (activity) {
is AppCompatActivity -> activity.delegate.createView(parent, name, context, attrs)
else -> delegate.createView(parent, name, context, attrs)
}
}
override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {
return checkAndReturnView(name, context, attrs, checkAndCreateView(parent, name, context, attrs))
}
override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
return null
}
fun checkAndReturnView(name: String, context: Context, attrs: AttributeSet, view: View?): View? {
val view = view ?: try {
createViewGroup(name, context, attrs)
} catch (e: Exception) {
e.toString().e()
null
} ?: return null
handlerXmlText(view, attrs)
return view
}
private fun handlerXmlText(view: View, attrs: AttributeSet) {
if (view is TextView) {
val value = getStringValue(attrs, true, "text")
if (value != null)
view.text = value
}
if (view is EditText) {
val value = getStringValue(attrs, true, "hint")
if (value != null)
view.hint = value
}
//下面兩個是自定義View使用了@string/
if (view is ItemView) {
val value = getStringValue(attrs, false, "left_text")
if (value != null)
view.setLeftText(value)
}
if (view is SelectView) {
val value = getStringValue(attrs, false, "middle_text")
if (value != null)
view.setMiddleText(value)
}
}
private fun Int.toText() = activity.getString(this)
private fun getStringValue(attrs: AttributeSet, isAndroidSystem: Boolean, valueName: String): String? {
val value = attrs.getAttributeValue(if (isAndroidSystem) ANDROID_KEY else APP_KEY, valueName)
if (value?.startsWith("@") == true)
try {
return value.substring(1).toIntOrNull()?.toText()
} catch (e: Exception) {
e.upload()
}
return null
}
private fun createViewGroup(name: String, context: Context, attrs: AttributeSet): View? {
return when (name) {
//下面兩個是自定義View使用了@string/
//且下面兩個是ViewGroup,如果是View則會在delegate中就創建完成
"com.xxx.ItemView" -> ItemView(context, attrs)
"com.xxx.SelectView" -> SelectView(context, attrs)
else -> null
}
}
}
最后把兩種方式一塊使用,然后就ok了(應該不會有人只用xml或只用getString()吧)
擴展
多語言使用程序中可能會遇見類似阿拉伯語的從右往左的習慣,其文字也是從右往左看的,這時需要將類似paddingLeft和paddingRight改成paddingStart和paddingEnd,更多的多語言適配可以參考安卓官網:https://developer.android.com/training/basics/supporting-devices/languages?hl=zh-cn#kotlin
然后獲取是否是從左到右的api:
fun isLTR(context: Context): Boolean {
return context.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_LTR
}
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/245326.html
標籤:其他
上一篇:Android 微信登陸
