如何在 Android Strings.xml 中搜索字符串?
Posted
技术标签:
【中文标题】如何在 Android Strings.xml 中搜索字符串?【英文标题】:How to search for a String in Android's Strings.xml? 【发布时间】:2020-10-30 15:45:24 【问题描述】:我试过这个答案:How to search content of strings stored in XML file?:
companion object
val TAG: String = "EffectsDescription"
fun fromStringsXml(string: String, context: Context): String
val ss = string.toLowerCase().replace(" ", "_");
Log.d(TAG, "gonna search for " + ss);
val s = searchForString(ss, context);
Log.d(TAG, "found: " + s);
return s ?: "ERROR"
private fun searchForString(message: String, context: Context): String?
return try
val resId: Int = context.resources.getIdentifier(message, "string", context.packageName)
Resources.getSystem().getString(resId)
catch (e: Exception)
null
我是这样从 Java 调用的:
EffectDescription.Companion.fromStringsXml(effectOrCategory, MainActivity.this.getApplicationContext())
但我得到所有变量的ERROR
。我正在记录它们只是为了查看它们是否与我的 strings.xml
中的字符串匹配并且它们匹配。例如我有
<string name="distortion">Distortion</string>
它说
gonna search for distortion
found: null
【问题讨论】:
【参考方案1】:修复:
fun fromStringsXml(string: String, context: Context): String
val ss = string.toLowerCase().replace(" ", "_");
Log.d(TAG, "gonna search for " + ss + " with packageName " + context.packageName);
val s = searchForString(ss, context);
Log.d(TAG, "found: " + s);
return s ?: "ERROR"
private fun searchForString(message: String, context: Context): String?
return try
val resId: Int = context.resources.getIdentifier(message, "string", context.packageName)
Log.d(TAG, "redID: $resId")
context.resources.getString(resId)
catch (e: Exception)
null
【讨论】:
以上是关于如何在 Android Strings.xml 中搜索字符串?的主要内容,如果未能解决你的问题,请参考以下文章
Android strings.xml 最佳实践? [关闭]
Proguard 不会混淆 android 中的 strings.xml
Android Studio 对 strings.xml 文件进行排序以匹配