You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何根据textView1匹配的资源名让textView2显示对应字符串

动态匹配字符串资源名展示对应内容实现方案

核心思路

Android编译后会给所有资源生成唯一int类型ID,无法直接通过strings.xml中定义的name属性值读取内容,需要通过Resources.getIdentifier()方法匹配资源名拿到对应ID,再读取字符串内容赋值给目标TextView。

基础实现代码

首先确认你的字符串资源已经按规则定义在res/values/strings.xml中:

<string name="a">Apple</string>
<string name="b">Banana</string>
<string name="c">Car</string>

Kotlin 实现(Activity/Fragment中)

// 读取textView1的文本,去除首尾空白避免空格导致匹配失败
val targetResName = textView1.text.toString().trim()
val resId = resources.getIdentifier(targetResName, "string", packageName)

// 容错判断:resId为0代表没有匹配到对应资源,避免崩溃
textView2.text = if (resId != 0) {
    getString(resId)
} else {
    // 匹配失败时的默认展示内容,可根据业务需求修改
    "无匹配结果"
}

Java 实现(Activity中)

String targetResName = textView1.getText().toString().trim();
int resId = getResources().getIdentifier(targetResName, "string", getPackageName());

if (resId != 0) {
    textView2.setText(getString(resId));
} else {
    textView2.setText("无匹配结果");
}

注意事项

  • 如果在Fragment中使用上述代码,需要通过requireContext()获取resources和包名,避免空指针:
    val context = requireContext()
    val resId = context.resources.getIdentifier(targetResName, "string", context.packageName)
    
  • getIdentifier()是反射匹配,性能比直接引用资源ID低,不要在列表高频绑定、绘制回调等场景反复调用。如果匹配项固定且数量少,推荐用直接映射的写法,性能更好:
    // 提前建立名称和资源ID的映射
    val resMap = mapOf(
        "a" to R.string.a,
        "b" to R.string.b,
        "c" to R.string.c
    )
    val targetResName = textView1.text.toString().trim()
    textView2.text = resMap[targetResName]?.let { getString(it) } ?: "无匹配结果"
    
  • 必须加resId为0的判断,传入不存在的资源名时getIdentifier()会返回0,直接调用getString(0)会抛出Resources.NotFoundException导致崩溃。

内容的提问来源于stack exchange,提问作者aungban service

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:18:39