【问题标题】:How to search for a String in Android's Strings.xml?如何在 Android 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

【问题讨论】:

    标签: java android android-layout kotlin


    【解决方案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
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2012-02-02
      • 2011-10-31
      • 2011-12-13
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多