Kotlin报Unexpected Tokens错误:代码行意外标记问题求助
解决Kotlin中
EditText findViewById(...)的语法错误 嘿,这个错误我之前刚踩过坑!咱们来一步步拆解问题:
错误原因
你写的代码editTextUsername = EditText findViewById(R.id.email_edittext)违反了Kotlin的语法规则——你把两个独立的表达式硬凑在了一行:
EditText是试图调用EditText类的构造函数(需要传入Context参数)findViewById(R.id.email_edittext)是获取布局中已存在的EditText控件
Kotlin编译器搞不懂你到底是想新建一个EditText实例,还是想获取布局里的控件,所以抛出了「Unexpected tokens」的错误。
正确的写法
根据你的需求(获取布局中的用户名输入框),有两种常用的正确写法:
1. 传统findViewById写法
Kotlin不需要像Java那样强制类型转换,直接调用findViewById即可,编译器会自动推断类型:
// 如果你已经提前声明了变量 editTextUsername = findViewById(R.id.email_edittext) // 或者直接声明并初始化 val editTextUsername: EditText = findViewById(R.id.email_edittext)
2. 官方推荐的视图绑定(View Binding)
现在更推荐用视图绑定来替代findViewById,不仅更安全(避免空指针和类型错误),写法也更简洁:
- 首先在模块的
build.gradle中开启视图绑定:
android { ... buildFeatures { viewBinding true } }
- 在Activity中初始化绑定类,直接通过绑定对象获取控件:
private lateinit var binding: ActivityMainBinding // 替换成你的布局对应的绑定类 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // 直接获取控件 val editTextUsername = binding.email_edittext }
为什么你的写法不对?
你可能是受Java写法的影响(Java中需要(EditText) findViewById(...)),但Kotlin里不需要这种显式转换,而且绝对不能把EditText和findViewById直接连在一起写——这会让编译器误以为你要同时执行两个无关的操作,从而触发语法错误。
内容的提问来源于stack exchange,提问作者LeALeg89
相关产品推荐
相关产品推荐

