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

Android Studio中Kotlin的findViewById报错求助:Unexpected tokens

解决Kotlin中findViewById报错"Unexpected tokens (use ';' to separate expressions on the same line)"的问题

常见修复方案:

  • 初始化时机错误:如果在类成员位置直接调用findViewById,会因布局未加载触发语法/逻辑错误。比如错误写法:

    class MainActivity : AppCompatActivity() {
        val signUpText = findViewById(R.id.signUpText) // 报错位置
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    }
    

    修正:将findViewById移到onCreate方法内部,且必须在setContentView之后执行:

    class MainActivity : AppCompatActivity() {
        private lateinit var signUpText: TextView
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            signUpText = findViewById(R.id.signUpText)
        }
    }
    
  • 同一行多表达式未分隔:检查代码是否在同一行写了多个赋值/调用语句却未拆分或加分号。比如:

    signUpText = findViewById(R.id.signUpText) val otherView = findViewById(R.id.otherView)
    

    修正:拆分为两行,或用;分隔:

    signUpText = findViewById(R.id.signUpText)
    val otherView = findViewById(R.id.otherView)
    
  • 推荐使用View Binding替代findViewById:这是官方推荐的更安全简洁的方式,避免手动ID匹配错误:

    1. 在模块级build.gradle中启用View Binding:
      android {
          ...
          buildFeatures {
              viewBinding true
          }
      }
      
    2. 在Activity中使用:
      class MainActivity : AppCompatActivity() {
          private lateinit var binding: ActivityMainBinding
      
          override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate(savedInstanceState)
              binding = ActivityMainBinding.inflate(layoutInflater)
              setContentView(binding.root)
              // 直接通过binding访问控件,无需findViewById
              binding.signUpText.text = "立即注册"
          }
      }
      

内容的提问来源于stack exchange,提问作者Shi Eng Ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:25:38