How to search for a String in Android's Strings.xml?

拥有回忆 提交于 2020-07-10 10:27:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!