动态更新 strings.xml 是不可能的,但有一个解决方案。当我想使用 Firebase Remote Config 进行 A/B 测试时,我遇到了同样的问题。所以我创建了FString https://github.com/ravindrabarthwal/FString/Android 库,它提供了一个智能解决方案。目前它的权力移动 Android 应用程序 https://play.google.com/store/apps/details?id=app.mouve.androidbase1关于生产。
安装
implementation 'com.ravindrabarthwal.fstring:fstring:1.0.0'
import com.example.myapp.R.string as RString // Import your string
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
FString.init(RString::class.java) // Initializes the FString
}
}
Usage
访问字符串
// This is how you get strings without FString
context.getString(R.string.my_app_name) // This is how you normally do
// To get the string using FString use
FString.getString(context, R.string.my_app_name)
// If you prefer extension function use
context.getFString(R.string.my_app_name) // This is how FString works ;)
更新字符串值
/*
* Assume this JSON is coming from server. The JSON string
* must be parseable to a JSON object with key and value pairs
*/
var jsonFromServer = """
{
"my_app_name": "MyApp v2.0",
"some_other_string": "this is so cool",
}
""".trimIndent()
// This will update the SharedPreference using keys from
// above JSON and corresponding value. The SharedPreference will
// not save any key that is not is strings.xml
FString.update(context, jsonFromServer)
查看库文档以获取更多信息。如果您发现答案有帮助,请投票并将其标记为答案。