问题
I tried this answer: 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
}
}
}
and I'm calling from Java like this:
EffectDescription.Companion.fromStringsXml(effectOrCategory, MainActivity.this.getApplicationContext())
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>
and it says
gonna search for distortion
found: null
回答1:
Fix:
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
}
}
来源:https://stackoverflow.com/questions/62825160/how-to-search-for-a-string-in-androids-strings-xml