如何在Android的Strings.xml中搜索字符串? [英] How to search for a String in Android's Strings.xml?
本文介绍了如何在Android的Strings.xml中搜索字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了以下答案:如何搜索内容存储在XML文件中的字符串?:
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打电话的:
and I'm calling from Java like this:
EffectDescription.Companion.fromStringsXml(effectOrCategory, MainActivity.this.getApplicationContext())
但是所有变量我都得到ERROR
.我正在记录它们,只是为了查看它们是否匹配我的strings.xml
中的字符串并且它们确实匹配.例如我有
but I get ERROR
for all variables. I'm logging them just to see if they match strings in my strings.xml
and they do. For example I have
<string name="distortion">Distortion</string>
它说
gonna search for distortion
found: null
推荐答案
修复:
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中搜索字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文