我是Kotlin的新手,我不知道如何解决这个错误:未解决的参考:视图。我的目标是按下按钮转到其他活动。我复制代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.button).setOnClickListener{
sendMessage(view)
}
}
val EXTRA_MESSAGE = "com.example.monedas.MESSAGE"
fun sendMessage(it: view) {
val intent = Intent(this, ListActivity::class.java)
val editText : TextView = findViewById(R.id.textView4)
val message = editText.text.toString()
intent.putExtra(EXTRA_MESSAGE, message)
startActivity(intent)
}
}
您正在将未定义的参数传递给sendMessage()
函数。
你没有在任何地方声明这个view
变量。
但似乎你不需要它,因为你不需要it
的sendMessage()
参数。
所以改为:
fun sendMessage() {
val intent = Intent(this, ListActivity::class.java)
val editText : TextView = findViewById(R.id.textView4)
val message = editText.text
intent.putExtra(EXTRA_MESSAGE, message)
startActivity(intent)
}
并称之为:
findViewById<Button>(R.id.button).setOnClickListener{
sendMessage()
}
作为旁注:
在Kotlin中,如果要访问活动类中膨胀布局的findViewById()
s,则不需要使用View
。
只需确保您已导入:
import kotlinx.android.synthetic.main.activity_main.*
然后你可以简单地做:
button.setOnClickListener{ sendMessage() }
在sendMessage()
:
fun sendMessage() {
val intent = Intent(this, ListActivity::class.java)
intent.putExtra(EXTRA_MESSAGE, textView4.text)
startActivity(intent)
}