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

如何按数组索引访问并遍历View Binding以设置文本值?

如何通过数组索引访问View Binding并设置字符串资源文本
  • 首先要明确:你不能直接存储R.id值到数组,因为R.id是整数类型,并非View Binding生成的实际View实例。正确的做法是把Binding中对应的View对象存入数组:

    // 替换成你的实际布局绑定类,比如ActivityMainBinding
    val textViewList = arrayOf(binding.bnd1, binding.bnd2, binding.bnd3)
    
  • 如果要使用strings.xml中的资源设置文本,不要直接赋值字符串,而是调用setText(int resId)方法,这样系统会自动识别并加载对应的字符串资源:

    textViewList[0].setText(R.string.hello_world)
    textViewList[1].setText(R.string.hello_again)
    textViewList[2].setText(R.string.some_text)
    
  • 要是需要批量遍历设置,还可以结合字符串资源数组使用forEachIndexed简化代码:

    val stringResources = arrayOf(R.string.hello_world, R.string.hello_again, R.string.some_text)
    textViewList.forEachIndexed { index, textView ->
        textView.setText(stringResources[index])
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:23:20